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) {
   $table->id();
   $table->string('name');
   $table->float('price');
   $table->text('description');
   $table->timestamps();
});

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

Schema::create('stores', function (Blueprint $table) {
   $table->id();
   $table->string('name');
   $table->string('address');
   $table->timestamps();
 });

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) {
            $table->id();
            $table->bigInteger('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products');
            $table->bigInteger('store_id')->unsigned();
	        $table->foreign('store_id')->references('id')->on('stores');
	        $table->timestamps();
});

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.

$product->stores

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

$store->products

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.