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

thebigk's avatar
Level 13

Does Query Builder's "chunk" know about database changes?

Consider this query -

DB::table('xyz')->whereNull('status')->orderBy('id')->chunk(50, function($posts) {

foreach($posts as $post) {
if($something) {
DB::table('xyz')->where('post_id', '=', $post->id)->update(['status' => 1]);
}
}
});

In this case, does Laravel know that the 'status' of several posts were updated in the first batch of 50; and avoid fetching those records in the next batch?

0 likes
1 reply
Sergiu17's avatar

https://laravel.com/docs/9.x/eloquent#chunking-results

If you are filtering the results of the chunk method based on a column that you will also be updating while iterating over the results, you should use the chunkById method. Using the chunk method in these scenarios could lead to unexpected and inconsistent results. Internally, the chunkById method will always retrieve models with an id column greater than the last model in the previous chunk:

Flight::where('departed', true)
    ->chunkById(200, function ($flights) {
        $flights->each->update(['departed' => false]);
    }, $column = 'id');
1 like

Please or to participate in this conversation.