Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent return count of each group with groupBy()

I want to groupBy() task using Laravel Eloquent. I have searched Internet and didn't find anything with eloquent. some people used groupBy() query with Query Builder like this link

But I want to create query like this style:

Task::select('id')->groupBy('category_id')->count();

This code just return only count of first category_id. But I want count of all the category_id.

like image 619
paranoid Avatar asked Aug 02 '16 09:08

paranoid


3 Answers

Native Collection alternative (grouped by php, not mysql). It's a nice option when you have the Collection as variable already assigned. Of course is less optimal than mysql grouping in most cases.

$tasks->groupBy('category_id')->map->count();
like image 84
Marek Gralikowski Avatar answered Nov 11 '22 12:11

Marek Gralikowski


More simple:

Task::select('id')->groupBy('category_id')**->get()**->count();
like image 32
Nacho Avatar answered Nov 11 '22 12:11

Nacho


You should add the count to the select function and use the get function to execute the query.

Task::select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();

The \DB::raw() function makes sure the string is inserted in the query without Laravel modifying its value.

like image 4
Jerodev Avatar answered Nov 11 '22 10:11

Jerodev