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 the total number of users?
User::chunk(200, function($users) { return count($users); });
This returns NULL. Any idea how I can get a return value from the chunk function?
Edit:
Here might be a better example:
$processed_users = DB::table('users')->chunk(200, function($users) { // Do something with this batch of users. Now I'd like to keep track of how many I processed. Perhaps this is a background command that runs on a scheduled task. $processed_users = count($users); return $processed_users; }); echo $processed_users; // returns null
As we know, the find () method in Laravel can be used by any user along with an array of primary keys, and it will return a set of matching records from the database.
After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.
Laravel Eloquent Chunk() Method Basically, Laravel eloquent chunk method break the large group of data set into smaller group of data set (chunks). Suppose, if you work with any big laravel apps and work with large group of records from the database.
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
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
$regions = array(); Regions::chunk(10, function($users) use (&$regions ) { $stickers = array(); foreach ($users as $user) { $user->sababu = ($user->region_id > 1)? $user->region_id : 0 ; $regions[] = $user; } }); echo json_encode($regions);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With