In Laravel, a Lazy Collection is a collection that defers its processing until the data is actually needed. This can be useful for working with large datasets, as it allows you to process the data in a more memory-efficient way.
A Lazy Collection is created by calling the LazyCollection::make
method and passing it a callback function that returns an iterator. The callback function will be executed when the data is needed, and the iterator will be used to retrieve the data from the callback.
Here’s an example of how you can use a Lazy Collection to process a large dataset:
$users = LazyCollection::make(function () {
$handle = fopen('users.csv', 'r');
while ($row = fgetcsv($handle)) {
yield $row;
}
});
$users->filter(function ($user) {
return $user['age'] > 18;
})->each(function ($user) {
// Process the user
});
In the example above, the LazyCollection::make
method creates a Lazy Collection that reads the data from the users.csv
file one row at a time. The filter
method filters the collection to include only users with an age greater than 18, and the each
method processes each user in the filtered collection.
Since the Lazy Collection defers its processing until the data is actually needed, the entire dataset is not loaded into memory at once. This can be more memory-efficient than loading the entire dataset into a regular Collection and then filtering and processing it.