Can I use Eloquent's count() with groupBy()?

Posted 6 months ago by RoboRobok

I would like to count games by is_released flag. I did it like that:

Game::select('is_released', DB::raw('count(*)'))
    ->groupBy('is_released')
    ->pluck('count(*)', 'is_released');

Another way to express the same thing is:

Game::select('is_released')
    ->selectRaw('count(*)')
    ->groupBy('is_released')
    ->pluck('count(*)', 'is_released')

It works, but can it be simplified, using Eloquent's count() method instead of DB::raw() or selectRaw()? Or maybe there is another way to simplify it? Currently I'm having is_released mentioned 3 times per call, which seems a lot.

(I'm just curious)

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.