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

davy_yg's avatar
Level 27

Chunk

Hello,

What this means:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
        foreach ($users as $user) {
            //
        echo $user;
        }
});

Processing 100 records at a time? Printing 100 user at a time?

How about the row 101 etc. ? Will it print them?

ref: https://laravel.com/docs/6.x/queries#chunking-results

0 likes
10 replies
davy_yg's avatar
Level 27

Okay, the code that I write, supposing that I put it in the view.

echo $user;

What will be printed?

Snapey's avatar

whatever is in $user ????

(but only if it is a string obviously)

1 like
davy_yg's avatar
Level 27

I mean 100 or 1000 rows? Suppose that table users has 1000 rows.

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    echo $user;
    }
});
jove's avatar

In the documentation you have linked yourself:

If you need to work with thousands of database records, consider using the chunk method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing. This method is very useful for writing Artisan commands that process thousands of records. For example, let's work with the entire users table in chunks of 100 records at a time:

https://laravel.com/docs/6.x/queries#chunking-results

ftiersch's avatar

It will print 1000 rows, but it will do so executing 10 database queries (fetching 100 rows, printing them, fetching the next 100 rows, printing them etc).

Snapey's avatar

get 100, loop over 100, get next 100, loop over 100 etc etc until all the records have been output

Snapey's avatar

NO

I ask you to 100 tins of food from the shop, but you can only carry 10, so you fetch 10 then go back and get another 10, then another 10 until I have the 100

The request was for 100 tins (total records) but you could only carry 10 at a time (memory restriction)

3 likes
jlrdw's avatar

So it's row 1 - 100 ?

  • First pass ========== row 1 - 100
  • second pass ========== row 101 - 200
  • third pass ========== row 201 - 300

Of course "chunk" is also covered in the docs.

Please or to participate in this conversation.