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

sl0wik's avatar

Chunking queries

Hi guys, I would like to share one quick tip. It might be obvious for some but for others a big time saver.

Tip: In Laravel ->each() method on query builder does chunking by default (1000 items per chunk), and you can set chunk size using the second parameter, for example, User::each(function($user) {...}, 500);.

Ref.: https://github.com/laravel/framework/blob/5.7/src/Illuminate/Database/Concerns/BuildsQueries.php#L58

0 likes
4 replies
jlrdw's avatar

You can specify size, second argument is the callback.

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    // Process the records...

    return false;
});
sl0wik's avatar

@jlrdw yeap - that's the way I used to chunk until I discovered I can use User::each(function($user) {...}); and Laravel will handle chunking behind scenes by default.

jlrdw's avatar

Also you have this under laravel, you may want to change it to guides or tips. Just a thought.

sl0wik's avatar

Good tip :). Thanks - moved to Tips.

Please or to participate in this conversation.