You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Attach, detach and sync many-to-many relationships in Laravel
1.attach is insert value to pivot table relation
when we run this code $user->roles()->attach([3]); that will be add/insert data to table user_role
role_id
user_id
3
1
2.sync is add value and delete to pivot table relation
If user_role table have
role_id
user_id
1
1
2
1
// run this syntax$user->roles()->sync([3, 2])
role_id
user_id
2
1
3
1
3. detach is remove value in pivot table relation
If we have data like this
role_id
user_id
2
1
3
1
1
1
when we try to run this code $user->roles()->detach(); that will be remove all data, but if we add the arguments on function detach $user->roles()->detach(1); will remove only role_id : 1
role_id
user_id
4. syncWithoutDetaching is add value without detach and duplicate when run twice
Let say we have table with value like this
role_id
user_id
3
1
when we insert using code syncWithoutDetaching example $user->roles()->syncWithoutDetaching([1, 2]); will be insert value role_id 1 and 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters