In this tutorial, i will show you many to many eloquent relationship in laravel. Many To Many eloquent relationship is slight hard compare to one to one and one to many relationship.
Lets understand many to many eloquent relationship with product and customer example. Customers can purchase various products, and products can be purchased by many customers
Lets define relationship words with our example:
Many (Multiple Customers) To (Has) Many (Multiple Products)
We can define many to many relationship using belogsToMany
method in respective model.
Here most important thing is, many to many relationship require three database models, two main models (i.e. products
and customers
in our example) and one intermediate or pivot table (i.e. customer_product
) which will store the foreign keys (i.e. customer_id
and product_id
) pointing to each related pair of records.
Now lets start many to many eloquent relationship example step by step.
First install fresh laravel using below command. If you have laravel installed then you can skip this part.
composer create-project --prefer-dist laravel/laravel many-to-many
Now update database credentials in .env
file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=many-to-many DB_USERNAME=root DB_PASSWORD=
Now run default migrations using below command. You can check them under database/migrations
directory. While running php artisan migrate
command laravel creates database tables from migrations.
php artisan migrate
You have successfully installed laravel and you can check it by enabling server using below artisan command.
php artisan serve
Now navigate http://127.0.0.1:8000
in your browser. You will see laravel welcome page.
Create Product Model And Migration File
Now lets create product model and migration using below artisan command.
php artisan make:model Product -m
Next open product migration file from database/migrations
directory and add some product related fields.
2019_11_27_231125_create_products_table.php
/** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('product_name'); $table->string('product_price'); // You can add more fields if you need $table->timestamps(); }); }
In product migration file, i have added product_name
, product_price
fields. You can add more if you require.
Next open product model file from app/
directory and $fillable
property to insert or update multiple records in single operation.
Product.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'product_name', 'product_price' ]; }
Don’t forget to run php artisan migration
artisan command.
Create Customer Model And Migration File
Lets create customer model and migration file using below artisan command.
php artisan make:model Customer -m
Now open customer migration from database/migrations
directory and add some customer info related fields.
2019_11_27_233730_create_customers_table.php
/** * Run the migrations. * * @return void */ public function up() { Schema::create('customers', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('firstname'); $table->string('lastname'); $table->string('email'); // You can add more filds if you need $table->timestamps(); }); }
Also update customer model as shown below.
Customer.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Customer extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'firstname', 'lastname', 'email' ]; }
Don’t forget to run php artisan migrate
command to create customers table in database.
Create Pivot Or Intermediate Table
In many to many relationship, we require intermediate table (Generally called pivot table) to store foreign keys of both tables. There is rule that pivot table should be in alphabetical order of two table names. Also pivot table should be singular name of both table connected with underscore(_).
Here we are going to make pivot table of customers
and products
table. So it should be name as customer_product
table. We can make it like product_customer
table but we need to pass extra arguments in belongsToMany
method. I will show you next part.
So lets create pivot table using below artisan command.
php artisan make:migration create_customer_product_table --create --table=customer_product
Now open migrations and add below schema in it.
2019_11_28_002257_create_customer_product_table.php
/** * Run the migrations. * * @return void */ public function up() { Schema::create('customer_product', function (Blueprint $table) { // $table->bigIncrements('id'); // -- Not Require // $table->timestamps(); // -- Not Require $table->unsignedBigInteger('customer_id'); $table->unsignedBigInteger('product_id'); }); }
Define Many To Many Relationship
Finally we reach at a stage where we need to define many to many relationship in the model. Many To Many relationship is defined by belongsToMany
method in model.
Lets define products
method on customer
model like this:
Customer.php
class Customer extends Model { // OTHER CODE /** * The products that belong to the customer. */ public function products() { return $this->belongsToMany('App\Product'); } }
The belongsToMany
method contain four arguments. The first argument is related model class, second one is for pivot table name (If you don’t follow conventional rule to define pivot table then you have to define pivot table name as second argument). The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Product', 'customer_product', 'product_id', 'customer_id');
Add or Remove Many To Many Relationship Data
Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let’s imagine a customer can have many products and a product can have many customers. To attach a products to a customer by inserting a record in the intermediate table that joins the models, use the attach
method:
$customer = App\Customer::find(1); $customer->products()->attach([1,2,3]);
To remove a many-to-many relationship record, use the detach
method. The detach
method will delete the appropriate record out of the intermediate table;
$customer->products()->detach([1,2,3]);
For convenience, attach
and detach
also accept arrays of IDs as input.
If you don’t want to use above attach
and detach
method, then you can use sync
method which will add or remove IDs from intermediate table. The sync
method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
$customer->products()->sync([1,2,3]);
Retrieve Many To Many Relationship Data
Once relationship is defined we can retrieve customer’s product using products dynamic property like this:
$customer = App\Customer::find(1); foreach ($customer->products as $product) { // }
You have to use products
dynamic property defined in customer
model. You can get all the products attached to customer by using above code.
Final Words
I hope that you may like this many to many relationship in laravel tutorial. You can also check our other tutorials like one to one eloquent relationship and one to many eloquent relationship. Feel free to ask me any query regarding many to many relationship in the comment box. Also please share this tutorial with your friends. Thank you friend 🙂