Lazy Collections in Laravel provide a memory-efficient way to work with large datasets by processing data one item at a time. They are especially useful for handling streams of data or iterating over large Eloquent queries without loading everything into memory.
Lazy Collections were introduced in Laravel 6, leveraging PHP Generators to enable on-demand processing of data, reducing memory usage in high-load scenarios.
Using Lazy Collections to process a large dataset:
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
for ($i = 0; $i < 1000000; $i++) {
yield $i;
}
})->each(function ($value) {
echo $value;
});
Lazy Collections with Eloquent:
User::cursor()->each(function ($user) {
echo $user->name;
});
This approach processes one user at a time, conserving memory and improving performance for large datasets.