Laravel Eloquent return count of each group with groupBy()

21,013

Solution 1

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

Solution 2

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.

Solution 3

More simple:

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

Solution 4

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.

Share:
21,013
paranoid
Author by

paranoid

I am beginner in laravel .

Updated on July 09, 2022

Comments

  • paranoid
    paranoid almost 2 years

    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.

  • sha-1
    sha-1 over 7 years
    Changing \DB::raw("count(id)") to \DB::raw("count(id) as total_count") would be more useful for further operation.
  • Simas Joneliunas
    Simas Joneliunas about 4 years
    please consider explaining what have you changed to make it work
  • Marek Gralikowski
    Marek Gralikowski about 4 years
  • Bilal Baraz
    Bilal Baraz almost 4 years
    This is helpful for my problem. It works by single line.