hashsalacop's avatar

How to return chunk() to json?

Hi, I am new here. I just want to ask. how do I return this into json?

 public function index()
{
        $NrMniDataUploaded = NrMniData::with('user')->chunk(1000, function($user){
                     foreach ($user as  $users) {
                             echo $users;
                          }     
                                                                  
        });
     return response()->json($NrMniDataUploaded);

}

Return output sample: {"id":9821,"user_id":null,"status_call":1}{"id":9821,"user_id":null,"status_call":1}true

its invalide json. I want to return a valid json.

0 likes
6 replies
grenadecx's avatar

Is the plan to only return the first 1000 users? Or do you want to return all the users?

Chunk is great when you need to fetch a lot of data that you need processing and you don't want to run out of memory, but if you need to return it as json, I don't see the point with chunk.

You are far better of just limiting the results or using pagination for this.

hashsalacop's avatar

Thank you for your reply.. but i think this is the only way for me to retrieve a thousand of data to fetch to my data tables. is there any way for me to convert it to JSON when return.?

grenadecx's avatar

I don't see how chunk solves that problem.

Chunk, in your case, would fetch 1000 users and store them in a collection. You would loop those 1000 users to print their names. and then it would fetch another 1000 users, store them in the same variable (collection) and so on. What this does is to make sure you don't run out of ram, since it will reuse the variable to store the data, so it wont keep all data in memory. Only a 1000 at a time.

At the best, using chunk this way you would allow you print the last 1000 users, since that what chunk does, the the previous data will be overriden with the last data. You could use chunk to create a new array with all the users, but then you could easily just have gotten all the users without chunk in the first place.

Chunk isn't the solution to this, it has a different purpose.

hashsalacop's avatar

do you have any suggestion? my goal is to display in a thousand data in one time. I'm using REST API.

hashsalacop's avatar

By the way, I'm using REST API and my idea is to display all the data from a thousand row and display it on the data tables.

1 like

Please or to participate in this conversation.