Laravel 8: how to manage Many-to-Many relationships with sync() method

Davide Cariola
3 min readFeb 17, 2022

If you’re using Laravel, you know that you can manage Many-to-Many relationships pretty easily.

An example of a many-to-many relationship is a library that has many best-seller books and those books are also shared by other libraries in the application.

So, a library has many books and a book has many libraries.

Usually, to define/manage the relationship between two resources, you can use the attach( ) method -to create the relationship- and the detach( ) method -to delete the Foreing Key Restraint-.

But Laravel also gives us a method called sync( ) to manage this type of relationship.

But what it does exactly? It syncronize the resources, automatically attaching the chosen ID’s and detaching the discarded ones.

It’s very easy to implement it:

From an Library object, we recall the relationship function and then we launch the sync( ) method, which accepts as parameters a series of ID’s, also in array form -in this case, the $request->books input-

It becomes very clear when using a <select> tag when creating a new Library resource.

With this result:

A <select> on a website page

What will happen in the case above? In the pivot table book_library, the library resource will be attached with the selected book resources and the unselected will be detached.

In a resource update scenario, the relationships related to that specific resource would be updated (attached or detached) based on the selected/unselected items on the form.

To help manage this scenario, I’ll leave here a useful snippet to give a better visual feedback to the user:

The contains( ) method accepts two parameters: the key to check -‘id’- and the value to find -’$book->id’-

With the if stated in the <option> tag, we’re usign the contains( ) method to check which books are related to the specific resource, to help the user for a better choice.

Let me know what you think! Follow me here on Medium for more Laravel tutorials and various tech-talk, on LinkedIn and on my site (for now, only in italian).

--

--

Davide Cariola

Backend and Laravel Specialist @ Aulab | Scrum Fundamentals Certified™ — follow me at davidecariola.it