Kairu
Kairu

Reputation: 194

Laravel chunk returns null

I'm needing to chunk my query as it's making PHP run out of memory, however the below code just dumps null:

$chunked = $query->chunk(25, function ($events) {
    //dd($events);
});
dd($chunked);

However, when I do the below, it dumps the first chunk of 25:

$chunked = $query->chunk(25, function ($events) {
    dd($events);
});
//dd($chunked);

No combination of changing dd($events); to the likes of return $events, return true, iterating over each item in each chunk and returning that - works.

Am I stupid/doing something wrong or is this not working like it should?

Upvotes: 1

Views: 1625

Answers (1)

lesssugar
lesssugar

Reputation: 16181

chunk() is a helper method which you can use on an instance of Query Builder or Eloquent Builder. In both cases, the method returns void:

This means that your $chunked variable will be always empty.

The syntax you need to employ is the following:

Query Builder

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

Eloquent

Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {
        //
    }
});

Basically, all you need to do is to use a loop within the callback function of chunk() to modify your results.

Upvotes: 1

Related Questions