Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cherson's avatar

Query Eloquent sum and groupBy

hello,

I have this SQL query that I would like to pass in Eloquent but I can't, can you help me?

SELECT SUM(number) as sum, types_id FROM coches
where membres_id = 40
group by types_id;
0 likes
5 replies
tykus's avatar
Coche::selectRaw('SUM(number) as sum, types_id')
	->where('membres_id', 40)
	->groupBy('types_id')
	->first();
MichalOravec's avatar
Level 75
$coches = Coche::select('types_id ', DB::raw('sum(number) as total'))
    ->where('membres_id', 40)
    ->groupBy('types_id ')
    ->get();
cherson's avatar

This is exactly the result I was waiting for, thank you for your help!

tykus's avatar

There should be only one result if the aggregator is a single value; in that case first would be preferable to get, right?

cherson's avatar

yes but in my case the aggregator is not unique and I need to get the sum of all the values by type

Please or to participate in this conversation.