This seems really simple (and probably is), but it doesn't seem to be covered in the documentation.
I have User objects, that can subscribe to a Category (many-to-many relationship). If I would delete a Category, I want to delete all the relations to all users (like, 'delete from user_subscriptions where category_id = X'). I can't seem to find a nice Eloquent way of doing this.
If I do something like
$category->subscribers()->delete();
I don't delete the relation, but the actual User objects, which is not what I want. Can someone enlighten me on how to remove all relations to an object in some Eloquent-friendly way?
Take a look at pivot tables: http://laravel.com/docs/eloquent#working-with-pivot-tables
For many-to-many, calling detach with no arguments will detach all:
$category->subscribers()->detach();
You can also use sync to override the entire collection of models and replace it with an empty list:
$category->subscribers()->sync([]);
Both are covered in the docs on many-to-many, but it's very easy to miss a lot of the variants (I don't think that many people even know about sync, for example).
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community