RoboPHP
RoboPHP

Reputation: 420

Laravel Chunk Returning Few Data - Laravel

I have about 2000 records in my database and i want to fetch them using view into my datatable.

When i run my code, i noticed my database is only showing 166 records. Why is that happening ?

Controller

 $chunks =  Items::
        where('is_active', 1)
        ->pluck('name','code','barcode','is_active')
        ->chunk(10);
        foreach ($chunks as $key => $chunk) {
            $chunks[$key] = array_values($chunk->toArray());
        }

     Log::info($chunks);
    return $chunks;

Upvotes: 0

Views: 913

Answers (1)

Anthony Aslangul
Anthony Aslangul

Reputation: 3857

Your problem is related to the way you retrieve your data:

 $chunks = Items::
        where('is_active', 1)
        ->pluck('name','code','barcode','is_active');

Here, you are misusing pluck(). This method returns an array (a Collection in this case but it's the same here) where the first argument is the value and the second argument is the key.

You are passing 4 parameters, the last two are useless.

Here is what's happening:

 $chunks = Items::
        where('is_active', 1)
        ->pluck('name','code'); //removed the last two parameters, they are not used

$chunks is a Collection, where the key is the code and the value is the name.

A Collection, like an array, cannot have the same key multiple times. Then, if two users share the same code, the second user will "overwrite" the first one. The third will overwrite the second and so on.

At the end, you'll have a Collection where the number of items will be equal to the number of unique code that are active (where('is_active', 1).

This why it fails.

How to fix this? Use get(), it does exactly what you expected pluck to do:

$chunks =  Items::
        where('is_active', 1)
        ->get(['name','code','barcode','is_active']) //be careful, array here
        ->chunk(10);
        foreach ($chunks as $key => $chunk) {
            $chunks[$key] = array_values($chunk->toArray());
        }

     Log::info($chunks);
    return $chunks;

Upvotes: 2

Related Questions