weekapaug
weekapaug

Reputation: 332

Multiple Fields with a GroupBy Statement in Laravel

Already received a great answer at this post

Laravel Query using GroupBy with distinct traits

But how can I modify it to include more than just one field. The example uses pluck which can only grab one field.

I have tried to do something like this to add multiple fields to the view as such...

$hats = $hatData->groupBy('style')
->map(function ($item){
  return ['colors' => $item->color, 'price' => $item->price,'itemNumber'=>$item->itemNumber];
});

In my initial query for "hatData" I can see the fields are all there but yet I get an error saying that 'colors', (etc.) is not available on this collection instance. I can see the collection looks different than what is obtained from pluck, so it looks like when I need more fields and cant use pluck I have to format the map differently but cant see how. Can anyone explain how I can request multiple fields as well as output them on the view rather than just one field as in the original question? Thanks!

Upvotes: 0

Views: 1639

Answers (1)

omitobi
omitobi

Reputation: 7334

When you use groupBy() of Laravel Illuminate\Support\Collection it gives you a deeper nested arrays/objects, so that you need to do more than one map on the result in order to unveil the real models (or arrays).

I will demo this with an example of a nested collection:

$collect = collect([
        collect([
            'name' => 'abc',
            'age' => 1
        ]),collect([
            'name' => 'cde',
            'age' => 5
        ]),collect([
            'name' => 'abcde',
            'age' => 2
        ]),collect([
            'name' => 'cde',
            'age' => 7
        ]),
    ]);

    $group = $collect->groupBy('name')->values();

    $result =  $group->map(function($items, $key){

              // here we have uncovered the first level of the group 
              // $key is the group names which is the key to each group

                 return $items->map(function ($item){

                 //This second level opens EACH group (or array) in my case:

                    return $item['age'];
                });
    });

The summary is that, you need another loop map(), each() over the main grouped collection.

Upvotes: 1

Related Questions