John Davidson

php - Laravel chunk method returning bool instead of data

0 comments
Message:


I'm working with a Laravel 8 application and am trying to chunk a large set of data to reduce memory usage, however when I chunk my results and output my data I'm getting an empty array.


$someHistory = [];
$history = DB::table('data_profiler_agents')
->whereDate('created_at', '>=', Carbon::now()->subDays(30))
->whereDate('created_at', '<=', Carbon::now())
->orderBy('created_at', 'desc')
->chunk(1000, function ($agents) use ($someHistory) {
array_push($someHistory, $agents->toArray());
});

What am I missing?


I just need to return all my data in the same format as a ->get(), expect, chunk first.


I did try:


$someHistory = $history->flatten();

and


$someHistory = collect($history);

Neither of which seemed to work for me.



My Answer:
The issue here is that the chunk method in Laravel returns a boolean value, not the chunked data itself. You need to modify your code to collect the chunked data inside the callback function and then merge it into your final result array. Here's how you can do it:

php
$someHistory = [];

DB::table('data_profiler_agents')
->whereDate('created_at', '>=', Carbon::now()->subDays(30))
->whereDate('created_at', '<=', Carbon::now())
->orderBy('created_at', 'desc')
->chunk(1000, function ($agents) use (&$someHistory) {
$someHistory = array_merge($someHistory, $agents->toArray());
});

// Now $someHistory should contain all the chunked data


By using the `array_merge` function inside the callback function, you can collect all the chunked data into the `$someHistory` array. This way, you will have all the data in the same format as if you had used the `get()` method.

Rate this post

4 of 5 based on 7431 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us