Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AndySong's avatar

Lazy Collections working with DB

Route::get('/test', function () {

    $users = User::all();

    return 'done';
});

I understand that if I have many User records this code above would not work because of memory limit.

$users = User::cursor();

If I change it to cursor method, it's ok. As it's lazy and it will give records when I ask for it.

However, when it comes to DB query it still select * from 'users'.

Now, I am very confused,

  1. it seems like we still load all the records into memory, is it correct? but why this time memory is not a problem.

  2. Is it because $users = User::all(); this way it is in collection way in memory, whereas cursor is in another format? so it uses way less memory?

  3. Is it because Lazy Collection will stream data from DB? (I do not know how to express this properly, hopefully you can understand).

Any explanation is appreciated thanks !!!

0 likes
9 replies
jlrdw's avatar

It's explained here. https://laravel.com/docs/6.x/collections#lazy-collections

I see it like when you paginate a query. But in the collection you only retrieve so much at a time.

To me collections aren't worth it for most things, Just paginate or use chunk on the data. But for small data sets that need some calculations or something, then an array or collection is fine.

AndySong's avatar

@jlrdw I checked the docs before posting this thread, I understand how Lazy-collections works, but I do not know why there is no memory issue when using cursor method. Since it loads all the records into memory as well.

jlrdw's avatar
jlrdw
Best Answer
Level 75

It doesn't, from docs:

However, the query builder's cursor method returns a LazyCollection instance. This allows you to still only run a single query against the database but also only keep one Eloquent model loaded in memory at a time.

Note this part:

but also only keep one Eloquent model loaded in memory at a time.

1 like
jlrdw's avatar

If anything helped, can you show as answered, good luck with all of this.

AndySong's avatar

@jlrdw so, it's loading one by one, until you do not want it, whereas all is like gives you all at the same time,

is it correct?

Please or to participate in this conversation.