Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over a collection in laravel and aggregate it

I’ve a sample collection

#items: array:4 [▼
0 => Collection {#465 ▼
  #items: array:2 [▼
    "id" => 1
    "user_id" => 5
  ]
}
1 => Collection {#455 ▼
  #items: array:2 [▼
    "id" => 2
    "user_id" => 5
  ]
}
2 => Collection {#419 ▼
  #items: array:2 [▼
    "id" => 3
    "user_id" => 1
  ]
}
3 => Collection {#410 ▼
  #items: array:2 [▼
    "id" => 4
    "user_id" => 1
  ]
}
]
}

how can I aggregate the above collection to the below collection. It is the count of ids for every user_id’s.

#items: array:2 [▼
0 => Collection {#465 ▼
  #items: array:2 [▼
    "user_id" => 1
    "count" => 2
  ]
}
1 => Collection {#455 ▼
  #items: array:2 [▼
    "user_id" => 5
    "count" => 2
  ]
}
]
}

Any suggestions would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I recreated the collection with the following code.

$collection = collect([
    collect(['id' => 1, 'user_id' => 5]),
    collect(['id' => 2, 'user_id' => 5]),
    collect(['id' => 3, 'user_id' => 1]),
    collect(['id' => 4, 'user_id' => 1]),
]);

Assuming this structure, you can get the results by chaining a few methods.

use Illuminate\Support\Collection;

$collection
    ->groupBy('user_id')
    ->map(fn ($item, $key) => ['user_id' => $key, 'count' => $item->count()])
    ->values();
    // ->mapInto(Collection::class); // if you really need each item to be its own collection
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading