phplaravelgroup-byquery-builderpluck

Larvel Query Builder group By with pluck


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.


Solution

  • 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'),
          ];
       });