Home / Snippets / How to Delete Whole Collection In Laravel
How to Delete Whole Collection In Laravel cover

How to Delete Whole Collection In Laravel

3.7K

2 years ago

0 comments

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this