What is deferred loading with lazy collections in Laravel?

Answer

Lazy Collections use PHP generators to keep memory consumption low when working with very large datasets. User::cursor() returns a lazy collection — it uses a server-side cursor so only one model is held in memory at a time instead of loading all records. LazyCollection::make(fn() => yield from User::cursor())->filter(fn($u) => $u->age > 18)->take(100)->all(). File::lines(storage_path("large.csv")) reads a file line by line lazily. Key methods: takeWhile(), skipWhile(), remember() (cache already iterated items). The standard Collection loads everything into memory; LazyCollection is a drop-in replacement for memory-constrained operations. Always prefer cursor() over all() when processing millions of records in a command or queue job.