To delete a whole model collection in Laravel you can make use of the "delete()" method on the collection instance itself. Imagine you have a post and you want to delete the one with an id of 1, 2, 3, 4, 5 then you can write your code like below.
<?php
Post::query()
->whereIn('id', [1, 2, 3, 4, 5])
->delete();
If you are want to delete the relationship collection instance then you can specify the relationship method and right away call the "delete()" method.
Laravel Delete Whole Relationship Collection
For the code example below, the code will delete the post comments with an id of 1, 2, 3, 4, 5.<?php
Post::query()
->with(['comments' => fn ($query) {
$query->whereIn('id', [1, 2, 3, 4]);
}])
->comments()
->delete();
Leave a reply