How can I get the return value of a Laravel chunk?

前端 未结 2 899
情话喂你
情话喂你 2021-02-12 19:07

Here\'s an over-simplified example that doesn\'t work for me. How (using this method, I know there are better ways if I were actually wanting this specific result), can I get th

2条回答
  •  生来不讨喜
    2021-02-12 19:50

    I don't think you can achieve what you want in this way. The anonymous function is invoked by the chunk method, so anything you return from your closure is being swallowed by chunk. Since chunk potentially invokes this anonymous function N times, it makes no sense for it to return anything back from the closures it invokes.

    However you can provide access to a method-scoped variable to the closure, and allow the closure to write to that value, which will let you indirectly return results. You do this with the use keyword, and make sure to pass the method-scoped variable in by reference, which is achieved with the & modifier.

    This will work for example;

    $count = 0;
    DB::table('users')->chunk(200, function($users) use (&$count)
    {
        Log::debug(count($users)); // will log the current iterations count
        $count = $count + count($users); // will write the total count to our method var
    });
    Log::debug($count); // will log the total count of records
    

提交回复
热议问题