Skip to main content

Eloquent Relationship Explained (MANY TO MANY) with attach,detach,sync

When you create a brand new project you have users table and User model already by default.

So, now create another table with model:

php artisan make:model Role -m

This will create Role model as well as roles table.

Now as it is many to many relation. So we need a pivot table.

Pivot table naming convention:

role_user

Here role is written first as because alphabetically r comes before u. and laravel eloquent relationship takes in this way. So, you should remember this always. and use _ in between role and user. like: role_user


So, let's create role_user table.

php artisan make:migration create_role_user_table --create=role_user

naming covention of pivot says that role_user table is singular.

users table includes:
id
name,
email

pivot table role_user includes:
user_id
role_id

roles table includes:
id
name

migrate it all.

Many to Many Relation:

Go to User model and write:

public function roles(){
 return $this->belongsToMany('App\Role');
}

create a user from server.

Insert:
$user = User::find(1);
$role = new Role(['name'=>'Administrator']);

$user->roles()->save($role);

Show:
$user = User::findOrFail(1);
foreach($user->roles as $role){
 echo $role->name;
}

Update:
$user = User::findOrFail(1);

if($user->has('roles')){
   foreach($user->roles as $role){
     if($role->name == "Administrator" ){
        $role->name = 'subscriber';
        $role->save();
     }
   }
}

Delete:
$user = User::findOrFail(1);
$user->roles->delete();

or,

if you have many roles and suppose i want to delete id 4 of role.

then:

$user = User::findOrFail(1);
foreach($user->roles as $role){
   $role->whereId(5)->delete();
}

Attach:
attach means adding to role_user table.

$user = User::findOrFail(1);
$user->roles()->attach(6);

Downfall of attach:
if you keep executing $user->roles()->attach(6);
it will attach 1 6 many times in the role_user table.

Detach:
detach means deleting or taking it off from role_user table.

$user = User::findOrFail(1);
$user->roles()->detach(6);

it will detach all 1 6 from role_user table.

Or, if you want to detach all the role_user tables data.
then:
$user = User::findOrFail(1);
$user->roles()->detach();

Sync:
$user = User::findOrFail(1);

suppose we have role and role ids are 4 and 5.
and suppose our user id 1 has role number 5 attached to it.
but i want to attach role number 4 to user id 1.so to do that,

$user->roles()->sync([4]);

it will attach 1 4 in the place of/ replacing 1 5.
$user->roles()->sync([4]);

To sync mulitple:
$user->roles()->sync([4,5]);


Thanks for reading. Please share.

Comments