Laravel Many to Many Eloquent Relationship Tutorial
Many to many relationship is a little bit complicated than one to one and one to many relationships. An example of such a relationship is a user with may have multiple roles, where the role are also connected with multiple users. many to many relationship in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11.
So in this tutorial, you can understand how to create many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many relationship.
In this example, i will create "users", "roles" and "role_user" tables. each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see database table structure on below screen.
Many to Many Relationship will use "belongsToMany()" for relation.
Create Migrations:
Now we have to create migration of "users", "roles" and "role_user" table. we will also add foreign key with users and roles table. so let's create like as below:
users table migration:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
roles table migration:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
role_user table migration:
Schema::create('role_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')
->onDelete('cascade');
});
Create Models:
Here, we will create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.
User Model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user');
}
}
Role Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany(User::class, 'role_user');
}
}
UserRole Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserRole extends Model
{
}
Retrieve Records:
$user = User::find(1);
dd($user->roles);
$role = Role::find(1);
dd($role->users);
Create Records:
$user = User::find(2);
$roleIds = [1, 2];
$user->roles()->attach($roleIds);
$user = User::find(3);
$roleIds = [1, 2];
$user->roles()->sync($roleIds);
$role = Role::find(1);
$userIds = [10, 11];
$role->users()->attach($userIds);
$role = Role::find(2);
$userIds = [10, 11];
$role->users()->sync($userIds);
I hope you understand of many to many relationship...
*** Click On it and Read in Details of RelationShip types:
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent selectRaw() Query Example
- Laravel Eloquent Order By Query Example
- Laravel Eloquent exists() and doesntExist() Example
- Laravel Eloquent Where Query Examples
- Laravel Order By Relation Column Example
- Laravel Order By Relationship Sum Column Example
- Laravel Relationship Eager Loading with Condition Example
- Laravel Relationship Eager Loading with Count Example
- Laravel Relationship Where Condition Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to One Eloquent Relationship Tutorial
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Has Many Through Eloquent Relationship Tutorial
- Laravel One to Many Polymorphic Relationship Tutorial
- Laravel Many to Many Polymorphic Relationship Tutorial