Intermediate LevelLaravel
How do LazyCollections use PHP Generators to process gigabytes of data with low RAM?
❓ Interview Prompt: Explain LazyCollection, cursor(), PHP generators (yield), and streaming millions of database records without RAM exhaustion.
Standard Eloquent collections loading 100,000 database records into memory will cause PHP 'Memory Exhaustion' errors.
LazyCollection & cursor():
'LazyCollection' leverages PHP Generators ('yield') to stream records one-by-one or in chunks:
•
Execute 'User::cursor()': Reads records sequentially over an unbuffered SQL query, processing millions of rows using under 2MB of RAM!
Code Implementation Example
php
<?php
use AppModelsUser;
// Streams 1,000,000 users with constant low memory usage
User::cursor()->filter(fn ($user) => $user->is_active)->each(function ($user) {
// Process individual user...
});💡Streaming large database datasets using User::cursor() LazyCollection.
🎯 Interview Key Takeaway
Use LazyCollection and Model::cursor() to stream large datasets using minimal memory via PHP generators.
#LazyCollection#Generators#Memory Optimization#Intermediate
Back to all Laravel Questions→