Larvel Query Builder group By with pluck

90 Views Asked by At
id agent_id currency
1 A0001 IDR
2 A0002 MYR
3 A0001 THB

Example currently has a dataset as above. Is there a way using only 1 query builder to get the outcome like below?

Output:

[
        "agent_id" => "A0001",
        "currency" => [
            "IDR",
            "THB",
    ],
],
[
        "agent_id" => "A0002"
        "currency" => ["MYR"]
]

Basically like trying to pluck the currency under same agent.

1

There are 1 best solutions below

0
On BEST ANSWER

Found a solution for this problem

   $output = $output
    ->get()
    ->groupby('agent_id')
    ->map(function($rows){
      return [
        "agent_id" => $rows[0]['agent_id'],
        "currency" => $rows->pluck('currency'),
      ];
   });