How to delete single row in pivot table with laravel?

by haylee.mertz , in category: PHP Frameworks , 10 months ago

How to delete single row in pivot table with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 10 months ago

@haylee.mertz 

To delete a single row in a pivot table with Laravel, you can use the detach() method on the relationship that the pivot table belongs to. Here's an example:


Assuming you have a many-to-many relationship between two models and you want to delete a single row in the pivot table:

1
2
$user = User::find($userId);
$user->roles()->detach($roleId);


In this example, we are detaching a role from a user. Replace User with the name of your model and roles with the name of the relationship that defines the many-to-many relationship. $userId and $roleId should be replaced with the actual IDs of the user and role you want to detach.


Using the detach() method will remove the specified row from the pivot table.

Related Threads:

How to connect 3 table with a pivot table in laravel?
How to delete row from table in codeigniter?
How to create a pivot table laravel?
How to compare 2 pivot table in laravel?
How to get values from pivot table in laravel?
How to join two tables with a pivot table using laravel?