Home > Mobile >  Laravel groupBy and pluck some values
Laravel groupBy and pluck some values

Time:07-08

I am using laravel 8.x and building rest API project. I am stuck with a query.

I have a table

id name type color
1 Dog animal black
2 Dog animal yellow
3 Cat animal red
4 Cat animal white

I want to do something like that,

$animals->groupBy('name')->get()

and hope to get result like,

$animals=[
          {
           name: "dog",
           type: "animal",
           colors: ["black", "yellow"]
          },
          {
           name: "cat",
           type: "animal",
           colors: ["red", "white"]
          }
         ]

Anyone help me?

CodePudding user response:

I would use Laravel mapToGroups collection method

$data = Animal::get();

$animals = collect($data)->mapToGroups(function ($item) {
            return [$item['name'] => $item];
        })->map(function ($itemGoup, $name) {
            return [
                'name' => $name,
                'type' => data_get($itemGoup, '0.type'),
                'colors' => collect($itemGoup)->pluck('color')->unique()->values()->toArray(),
            ];
        })->values()->toArray();

with output:

[
    {
        "name": "Dog",
        "type": "animal",
        "colors": ["black", "yellow"]
    },
    {
        "name": "Cat",
        "type": "animal",
        "colors": ["red", "white"]
    }
]

CodePudding user response:

I will slightly improve the Erik answer.

        $data = Animals::get();

        $animals = collect($data)->groupBy('name')->map(function($item) {
            return [
                'name' => $item[0]['name'], // the name always the same
                'type' => $item[0]['type'], // if the type not change (as the name)
                'colors' => $item->pluck('color')->unique()->toArray(),
            ];
        })->values()->toArray();
  • Related