Bhutan's leading web hosting and web design company
Give us a call +975-77100394 . 17119075

Conditionally deleting rows from pivot tables in Laravel

To delete relations from many to many  tables using Laravel’s Eloquent, there’s the detach() method. The detach() method deletes all relationships in the pivot table for particular given IDs.

For example, if you have duplicate rows in the pivot table for the same Model (with different values in other fields), doing a detach on a particular ID will remove all rows with that ID.

Suppose our pivot table has the following:

id | movie_id | people_id | role |

1  |   1      |     1     | Director
2  |   1      |     1     | Producer

Doing a $movie->find(1)->detach(1) will remove all rows in the table. This is the expected result if you want to disassociate people with ID 1 from movie with ID 1. But if you want to just remove the row where the role is “Producer” for people ID 1, then the detach() method will not work.

Although not reflected in the official documentation, laravel provides two methods called newPivotStatement() and newPivotStatementForId().

With these you can achieve your result with:

$movie->find(1)->people()->newPivotStatement()->where('people_id',1)->where('role', 'Producer')->delete();


$movie->find(1)->people()->newPivotStatementForId(1)->where('id', 2)->delete();

Where 2 is the ID for the row ID in the pivot table.