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

patrykszady's avatar

orderBy or sortBy of groupBy sum

Hi all,

I'm trying to sortBy or orderBy the sum of amount from my groupBy...this is what I have in my controller

$expenses = $project->expenses()->groupBy('vendor_id')->get();

This returns the correct info but I'm not sure how to sort it so that the first result is the largest sum of AMOUNT for each vendor. Amount is stored in Expenses table together with vendor_id. Thank you in advance for any help!

0 likes
2 replies
patrykszady's avatar

Thanks, I'll have a look. For now the following works - I just think it's messy so I'll read over your link.

$expenses = $project->expenses()->select('*', DB::raw('sum(amount) as total'))->groupBy('vendor_id')->orderBy('total', 'DESC')->get();

Please or to participate in this conversation.