Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 6+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 02 Oct, 2025
  • 206 Views
  • Handle large datasets without eating up your server’s memory

Use lazy() for Memory-Friendly Collection Processing in Laravel

When dealing with thousands (or even millions) of records, loading them all into memory with all() or get() can slow down your app or even crash it. Laravel solves this problem with lazy(), a memory-efficient way to process records in chunks.

The Risky Way – Using all()

$users = User::all();
foreach ($users as $user) {
    // process each user
}

This loads every single row into memory at once. If you have 1 million users, your server might not survive.

The Laravel Way – Using lazy()

User::lazy()->each(function ($user) {
    // process each user without loading everything into memory
});

Instead of loading everything, lazy() fetches records in small chunks under the hood and streams them one by one.

Real-World Example

Imagine you want to send a notification to every user in the database:

User::lazy()->each(function ($user) {
    $user->notify(new ImportantUpdateNotification());
});

Even if you have millions of users, your memory usage stays low and predictable.


Share: