Many To Many Relationships Laravel


by Samarth Sinha on 2017-06-03 03:28:11

Attaching / Detaching

Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach() method:

$user = App\User::find(1);


When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

$user->roles()->attach($roleId, ['expires' => $expires]);

Of course, sometimes it may be necessary to remove a role from a user. To remove a many-to-many relationship record, use the detach(). The detach() will remove the appropriate record out of the intermediate table; however, both models will remain in the database:

// Detach a single role from the user...

// Detach all roles from the user...

For convenience, attach() and detach() also accept arrays of IDs as input:

$user = App\User::find(1);

$user->roles()->detach([1, 2, 3]);

$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);

Syncing Associations

You may also use the sync() to construct many-to-many associations. The sync() 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:

$user->roles()->sync([1, 2, 3]);

You may also pass additional intermediate table values with the IDs:

$user->roles()->sync([1 => ['expires' => true], 2, 3]);

If you do not want to detach existing IDs, you may use the syncWithoutDetaching():

$user->roles()->syncWithoutDetaching([1, 2, 3]);

About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.