Efficiently handling large Eloquent results in Laravel

We sometimes need to handle large results of models when working with Eloquent. If we use the regular method of retrieving the full result set and working with the models, then it’s going to overflow our memory – essentially failing the entire process.

In order to bring efficiency to that process, we can lazy load the models in chunks and process them. Laravel provides two methods for that: lazy() and lazyById().

Consider a scenario where in a console command, we need to update a course’s average rating (example from Laravel Courses). Here’s how we can do that using the lazy() method, where courses will be fetched in chunks, and we can work with each of the retrieved models individually:

use App\Models\Course;
 
foreach (Course::lazy() as $course) {
$course->updateAverageRating();
}

Consider another use case where we want to perform bulk updates to a model but want to do that in chunks. Let’s see how that can be achieved:

use App\Models\Invoice;
 
Invoice::where('status', 'pending')
->lazyById(100)
->each->update(['status' => 'abandoned']);

The official documentation also has some good examples you can look into as well.