15

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.

Community
  • 1
  • 1
paranoid
  • 6,799
  • 19
  • 49
  • 86

7 Answers7

30

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();
4

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.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
  • 3
    Changing **\DB::raw("count(id)")** to **\DB::raw("count(id) as total_count")** would be more useful for further operation. – sha-1 Aug 12 '16 at 20:50
3

More simple:

Task::select('id')->groupBy('category_id')**->get()**->count();
Mostafa Norzade
  • 1,578
  • 5
  • 24
  • 40
Nacho
  • 628
  • 1
  • 12
  • 19
1

This works for me.

output:

return $email_trackers = EmailTracker::get()->groupBy('campaign_id')->map->count();
     
{
  "6": 2
}
Pri Nce
  • 576
  • 6
  • 18
0

You can do something like this:

return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();
Mahmoud Zalt
  • 30,478
  • 7
  • 87
  • 83
0

I overrode the count() method in my model. Could be something like:

public function count($string = '*'){
    $tempmodel = new YourModel();
    return $tempmodel ->where('id',$this->id)->where('category_id',$this->category_id)->count($string);
}

This gave me exactly the behavior of count() I was looking for.

Fjonan
  • 41
  • 7
0

Worked for me as

we need to select one column like 'category_id' or 'user_id' and then count the selected column on get()

    Task::select('category_id')
           ->where('user_id',Auth::user()->id)
           ->groupBy(['category_id'])
           ->get()
           ->count();