Home » Source Book » Laravel: sync() With An Example

Laravel: sync() With An Example

Last updated on June 15, 2021 by

In this source book, we will study the concept of Laravel sync() function. While working with Many to Many relationships in Laravel we need to introduce an intermediate table which is called the Pivot table in Laravel terms. And to perform operations on this table we need to use methods, sync() is one of them. Let’s just explore it more in deep.

Table of Contents
1. Use Of Sync In Laravel
2. Example Of Sync In Laravel
3. Pass Additional Parameters In Sync
4. syncWithPivotValues() Method In Laravel
5. syncWithoutDetaching() Method In Laravel

01 Use Of Sync In Laravel

The sync() method accepts an array as an argument. As the name suggests, this method synchronizes the database entries that means whatever you pass in this method, those records will be kept into the database and the rest will be removed from the intermediate(pivot) table.

02 Example Of Sync In Laravel

Let’s say in our project, we need to define the roles of every user. So users can have many roles and inverse roles can have many users. Thus, it will be a Many To Many relationships.

To accomplish this we need to create 3 tables users, roles, and intermediate table role_user. The role_user table will have the user_id and role_id column which connects both users and roles table and this intermediate table called the pivot table.

Here are the table structures:

    id - integer
    name - string

    id - integer
    name - string

    user_id - integer
    role_id - integer

We have the following data in our database:


id  name        email            
--  -------     -------
1   John Doe 1  johndoe+1@example.com
2   John Doe 2  johndoe+2@example.com
3   John Doe 3  johndoe+3@example.com
4   John Doe 4  johndoe+4@example.com


id  name        created_at            updated_at
--  ----------  -------------------   ------------------
1   Admin       2021-05-27 13:00:32   2021-05-27 13:00:32
2   Subscriber  2021-05-27 13:00:32   2021-05-27 13:00:32
3   Editor      2021-05-27 13:00:32   2021-05-27 13:00:32
4   Viewer      2021-05-27 13:00:32   2021-05-27 13:00:32


id  user_id   role_id            
--  -------   -------
1      1         1
2      2         2
3      3         2
4      3         3
4      3         4

For example, As you can see in the role_user table a user with ID 2 has 3 roles, Editor, Subscriber, and Viewer. Now, we want to remove the Subscriber and Viewer role for that user but we want to retain the Editor role.

Our role_user table before sync() operation:

id  user_id   role_id            
--  -------   -------
1      1         1
2      2         2
3      2         3
4      2         4
5      3         2
6      4         3

	use App\Models\User;

	$user = User::find(2);

	// Want to keep only Editor (Id 2) role

After performing the above operation, our role_user table will look like below:

id  user_id   role_id            
--  -------   -------
1      1         1
2      2         2
5      3         2
6      4         3

03 Pass Additional Parameters In Sync

Sometimes, we may need to pass some additional data while syncing. For example, I would like to store status expires for the only user with ID1 then you can do as below:

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

04 syncWithPivotValues() Method In Laravel

If you would like to insert additional data for all the IDs so you don’t want to use the above way which takes time to write code and makes it complicated for many IDs, you may use the syncWithPivotValues method:

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

We have passed the active => true for all 3 records, you can see how code is prettier instead of writing [1 => ['active' => true], 2 => ['active' => true], 3 => ['active' => true] ]. So this is another and good way to pass additional parameters in bulk.

05 syncWithoutDetaching() Method In Laravel

The syncWithoutDetaching() method is used to attach multiple IDs without removing existing records. So you already know how sync() works, the sync() method will remove other IDs from the pivot table. This method only attaches the IDs without removing other IDs.

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

That’s it from our end. We hope this article helped you to understand Laravel sync method with an example.

Additionally, read our guide:

  1. Laravel: Pivot Table With An Example
  2. Laravel: Accessor With An Example
  3. Laravel: Mutators With An Example
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How To Dynamic iFrame URL In Elementor
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

7 thoughts on “Laravel: sync() With An Example”

  1. In your example role_user table you say
    As you can see in the role_user table a user with ID 2 has 3 roles, Editor, Subscriber, and Viewer.

    But it doesnt
    id user_id role_id
    — ——- ——-
    1 1 1
    2 2 2
    3 3 2
    4 3 3
    4 3 4


Leave a Comment