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:
users
id - integer
name - string
roles
id - integer
name - string
role_user
user_id - integer
role_id - integer
We have the following data in our database:
users
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
role
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
role_user
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
<?php
use App\Models\User;
$user = User::find(2);
// Want to keep only Editor (Id 2) role
$user->roles()->sync([2]);
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:
- Laravel: Pivot Table With An Example
- Laravel: Accessor With An Example
- Laravel: Mutators With An Example
- Laravel: Change Column Name In Migration
- How To Use Where Date Between In Laravel
- How To Add Laravel Next Prev Pagination
- Laravel Remove Column From Table In Migration
- Laravel: Get Month Name From Date
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Calculate Age From Birthdate
- How To Dynamic iFrame URL In Elementor
- How To Handle Failed Jobs In Laravel
- How To Remove WooCommerce Data After Uninstall
- How To Get Latest Records In Laravel
- How To Break Nested Loops In PHP Or Laravel
- How To Pass Laravel URL Parameter
- 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!
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
Hi Mathius,
Thanks for drawing attention to it. We will correct it.
Thanks, it is useful article.
We are glad that our article is useful to you. Thanks
Thanks, it is very useful article.
We are glad that our article is useful to you. Thanks
Can we pass objects in that sync parameter array