How Delete Multiple Records in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to delete multiple records in Laravel.

 

How to Delete Multiple Records in Laravel

To delete multiple records in Laravel, you can use the whereIn method on your Eloquent model and pass an array of IDs or a subquery to filter the records you want to delete. Then, you can call the delete method to remove the selected records.

Example -

$ids = [1, 2, 3];

// Delete records by IDs
MyModel::whereIn('id', $ids)->delete();

// Delete records using a subquery
MyModel::whereIn('id', function($query) {
    $query->select('id')->from('my_other_table')->where('is_deleted', true);
})->delete();

 

In the first example, we pass an array of IDs to the whereIn method to select the records to delete. In the second example, we use a subquery to select the records to delete based on a condition in another table.

Note that calling the delete method will permanently remove the records from the database. Use the delete method on a model that implements the SoftDeletes trait if you wish to soft-delete the records without actually removing them from the database.

Comments 0

Leave a comment