Level 73
This should do the trick.
DB:select(SELECT color, count(color) quantity FROM table GROUP BY color);
You can probably do it with eloquent all the way but this is a SQL solution.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
How would I query for a return count of unique column values?
So if my users have an attribute of color with optional values of red, blue, and green.
I want to return:
red => 15 blue => 33 green => 23
I can do this easily with individual queries such as:
Model::where('this', 'that')->count();
But I want to return all of them at once.
Thanks.
With Eloquent:
Model::select('color', DB::raw('count(color) quantity'))->groupBy('color')->get();
Please or to participate in this conversation.