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

thebigk's avatar
Level 13

Does "Chunk" actually make multiple queries?

I'm bit confused over the functioning of chunk.

Let's say I have a model User, and it's got 1000 entries. I want to build an array of ids of all the users.

I write -

User::all(). Now this would try to fetch all the 1000 records in one go. Which I believe would eat up lot of memory. The second approach would be to use -

User::chunk(50, function($user) {
    $ids[] = $user->id;
});

I want to understand whether the second approach would actually make 20 queries to the database to fetch all 1000 records in order to be light on memory. Or does it simply fetch all the records like User::all() and then divide the data into chunks of 50?

0 likes
4 replies
thebigk's avatar
Level 13

Thanks @bobbybouwmann. Good to know that it works that way. But then, what about this -

User::all()->chunk(50)

Does it work the same way or different?

Krisell's avatar

User::all() will run the query and store the result in a Collection. I didn't even know that a chunk-method existed there as well, but yes, that will run only ONE query and fetch all results, so any performance-improvement running on a large table will be lost.

Snapey's avatar

Your example is a bad one because it would be far more efficient to run one query and just pluck the value you need.

User::all()->chunk(50) is using the collection method not query builder method

https://laravel.com/docs/5.6/collections#method-chunk

(ie load all records into memory and then split it into smaller collections)

1 like

Please or to participate in this conversation.