Search code examples
phplaraveleloquent

Merge two collection with the same key and preserve the value


i have the following code :

$kategori = KategoriProduk::select('kategori_produks.nama as nama_kategori', 'tipe_produks.layanan as nama_tipe')
    ->leftJoin('tipe_produks', 'tipe_produks.kategori_produk_id', '=', 'kategori_produks.id')->get();

and the result is :

0 => [
   "nama_kategori" => "range hoods"
   "nama_tipe" => "A"
],
1 => [
   "nama_kategori" => "range hoods"
   "nama_tipe" => "B"
],
2 => [
   "nama_kategori" => "hobs"
   "nama_tipe" => "A"
],

and i want the result to something like this :

0 => [
   "nama_kategori" => "range hoods"
   "nama_tipe" => ["A", "B"]
],
1 => [
   "nama_kategori" => "hobs"
   "nama_tipe" => "A"
],

i tried using distinct() but the result isnt quite what i want. any help is appreciated! thanks!


Solution

  • You can use groupBy like this :

    $result = $kategori
        ->groupBy('nama_kategori')
        ->map(function ($items, $key) {
            // Get all 'nama_tipe' values from the grouped items
            $namaTipe = $items->pluck('nama_tipe');
            
            // If there's only one 'nama_tipe', return it as a string, otherwise return as an array
            return [
                'nama_kategori' => $key,
                'nama_tipe' => $namaTipe->count() === 1 ? $namaTipe->first() : $namaTipe->all()
            ];
        })
        ->values();