17

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.

7 Answers 7

33

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();
Sign up to request clarification or add additional context in comments.

2 Comments

This is helpful for my problem. It works by single line.
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.

1 Comment

Changing \DB::raw("count(id)") to \DB::raw("count(id) as total_count") would be more useful for further operation.
3

More simple:

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

2 Comments

This looks like invalid syntax. It does not compile on my side.
AFAIK ** is valid only as a mathematical operator, but probably the OP used it a some kind of pseudo code, which if not explained, is useless.
1

This works for me.

output:

return $email_trackers = EmailTracker::get()->groupBy('campaign_id')->map->count();
     
{
  "6": 2
}

Comments

0

You can do something like this:

return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();

Comments

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.

Comments

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

1 Comment

please consider explaining what have you changed to make it work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.