Ad

Elegant Way To Get 5 Counts From The Same Query In Laravel

- 1 answer

I have a query that gives me 200 results in 5 differents categories.

What I need is getting count of each categories.

What is the best way to do, make 5 counts or get the complete list, and process it ( it seems more heavy if I have to do a foreach)

Tx!

Ad

Answer

Laravel is awesome !

https://laravel.com/docs/5.1/collections#method-groupby

As I need the full list, I just get it once, and then I can apply groupby to a collection!

 $groups = $users->groupBy('categoryId');

And then I just do

@foreach($groups as $group)
  {{ sizeof($group) }}
@endforeach
Ad
source: stackoverflow.com
Ad