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.
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 !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With