Home » How To Update Pivot Table In Laravel

How To Update Pivot Table In Laravel

Last updated on June 8, 2021 by

In this tutorial, we will learn how to update the pivot table records in Laravel. 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.

Using the pivot attribute we can easily interact with this intermediate table on the models or in controllers.

Example Of Pivot Table 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      4         3

Update Pivot Table In Laravel

There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.

We have 3 tables as mentioned above but we have only two models User.php and Role.php but what about 3rd one? We don’t have that right? But the twist here, we can interact with the third role_user table using the following ways:

01 Using attach() Method

As per our database entry, For a user with ID 2 has a Subscriber role, we want to assign an additional role Editor to that user. Let’s do that.

The attach() method will simply insert new records into the intermediate(pivot) table.

<?php

	use App\Models\User;

	$user = User::find(2);

	$roleID = 3; // Editor role ID

	$user->roles()->attach($roleID);

We can also pass the array of IDs to attach multiple roles to the user.

$user->roles()->attach([2,3,4]);

02 Using detach() Method

The detach() method is inverse of attach() method, it will simply remove the records from the intermediate(pivot) table.

e.g. We recently attached a new role Editor to the user with ID 2. Let’s remove that role from that user.

<?php

	use App\Models\User;

	$user = User::find(2);

	$roleID = 3; // Editor role ID

	$user->roles()->detach($roleID);

We can also pass the array of IDs to remove multiple roles from the user.

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

Notes: if you don’t pass anything in detach() method then it will remove all the entries e.g. $user->roles()->detach();

03 Using sync() Method

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.

e.g. If 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

04 Using toggle() Method

As the name suggests, the toggle() method will “toggles” the IDs that means if you provide an array of IDs then if any of the IDs exist, it will remove those IDs from the database and If some of the provided IDs do not exist then it will insert the IDs.

e.g. If a user with ID 2 has 2 roles, Editor, Subscriber. Now, we want to remove both roles and want to add Viewer role for that user.

Our role_user table before toggle() operation:

id  user_id   role_id            
--  -------   -------
1      1         1
2      2         2
3      2         3
5      3         2
6      4         3
<?php

	use App\Models\User;

	$user = User::find(2);

	$user->roles()->toggle([2,3,4]); 

Our role_user table after toggle() operation:

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

The above example has removed the entries with ID 2 & 3 and inserted new records with ID 7.

Additionally, read our guide:

  1. Base Table Or View Already Exists In Laravel Migration
  2. Add Column After A Column In Laravel Migration
  3. Laravel: Change Column Type In Migration
  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
  18. How To Fix Elementor Icons Not Showing

That’s it from our end. We hope this article helped you to update pivot table in Laravel.

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!

 
 

Leave a Comment