How to delete single row in pivot table with laravel?

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

How to delete single row in pivot table with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 3 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.