Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel attach manytomany with extra field

Tags:

php

laravel

There are 3 tables. Products, Users and product_user. There are 3 fields in product_user table. product_id, user_id and price.

product_id and user_id will be attached and filled automatically. But I want a textfield named price which user fill it to be inserted in price field in database.

I mean I want to insert a textfield when attaching.

like image 627
Ali Lashini Avatar asked Jun 17 '17 08:06

Ali Lashini


1 Answers

To insert an extra field in your pivot table first of all, you need to specify this extra field in your models.

For Example this:

In Product model

public function users()
{
   return $this->belongsToMany('App\User', 'product_user')
                    ->withPivot('price');
}

In User model

public function products()
{
   return $this->belongsToMany('App\Product', 'product_user')
                    ->withPivot('price');
}

Furthermore, in you Controller you can attach this extra field like this:

$product->users()->attach($user_id, ['price'=> $price ]);

I hope this will help you !!!

like image 199
diakosavvasn Avatar answered Nov 02 '22 11:11

diakosavvasn