Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Efficiently deleting millions of records in Laravel

When working with large datasets, you might need to delete millions of records from the database at once. Doing so can be quite slow and resource-intensive. And in doing so, you might run into memory issues, timeouts, and other problems.

Matt Kingshott recently shared an interesting trick that can help you delete millions of records from the database efficiently.

Here’s how you can do it.

use App\Models\User;

$query = User::where('created_at', '<=', now()->subDays(30));

while ($query->exists()) {
    $query->limit(5000)->delete();

    sleep(3);
}

Essentially, the code above deletes 5000 records at a time and then sleeps for 3 seconds. And it continues to do so until there are no more records to delete.

This approach doesn’t make the database to fall over and it’s a lot more efficient than deleting all the records at once. I think this is genius and can be pretty helpful when you’re dealing with large datasets.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?