How to Use Many to Many Relationship in Laravel?

Imagine you have multiple stores and multiple products. Now every product can be available on many stores and each store has multiple products. How to implement that. Well Laravel makes it super easy and you can implement that in few minutes. First make few migrations.

1. Creating and running migrations

First we will create a table for products by using this code in products migration

 Schema::create('products', function (Blueprint $table) {

Then we will create store migration and put this code inside that.

Schema::create('stores', function (Blueprint $table) {

and now we need a pivot table called ‘products_stores’ where we will place product_id and store_id. It will tell us about product location and its respective store for the query we entered.

Schema::create('products_stores', function (Blueprint $table) {

Now run migrations and moving on to the models.

2. Creating Models

we need to place this code in Product model.

protected $fillable = ['name', 'price', 'description'];

public function stores(){
    	return $this->belongsToMany(Store::class, 'products_stores', 'product_id', 'store_id');

Now we will place this code in Store model.

protected $fillable = [ 'name', 'address' ];

public function products() {
	return $this->belongsToMany( Product::class, 'products_stores', 'store_id', 'product_id' );

3. Getting products and stores

Now we can get all stores where every product is available with the following command.


and every product which is available on each store with the following command.


4. Attaching and synching

The cool part is we can add products to stores or sync them anytime using simple queries.

$product = Product::findOrFail( 1 );
$stores  = [ 1, 2 ];
$product->stores()->attach( $stores );
$product->stores()->sync( $stores );

and this works fine for stores as well.

$store = Store::findOrFail( 1 );
$products = [ 1, 2 ];
$store->products()->attach( $products );
$store->products()->sync( $products );

I hope you understood everything about many to many relationship. It is super easy to implement in Laravel. If you have any questions please leave a comment.