Posts Learn Components Snippets Categories Tags Tools About
/

How to Delete Whole Collection In Laravel

Learn how to delete whole Model collection in Laravel the easy way

Created on Sep 29, 2021

3658 views

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();

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Delete Whole Collection In Laravel

)