Home > Software engineering >  Laravel Many to Many, how to insert/get data inside the pivot table?
Laravel Many to Many, how to insert/get data inside the pivot table?

Time:06-16

in laravel 9 I implement many to many relationship.

I have three table, shop , product and product_shop table.

each shop can have number of every single product. and each product can exist in multiple shops.

the question is how can I insert/get the number of product inside the product_shop table?

what relationship syntax I have to use?

product_shop table :

$table->unsignedInteger('product_id');
$table->unsignedInteger('shop_id');
$table->unsignedInteger('number');

$table->foreign('product_id')->references('id')->on('products');
$table->foreign('shop_id')->references('id')->on('shops');

thanks

CodePudding user response:

You can use pivot. For example,

$product = $shop->products()->withPivot(['number'])->first();
$number = $product->pivot->number;

And if you want to insert,

$shop->products()->attach([$product_id => ['number' => $your_value]]);
  • Related