Laravel Eloquent – Sum with Group By

Using Sum with Group by in Eloquent

Have you ever run across code that loops through a collection only to add up a total. This is a good place to improve the efficiency of the code by instead performing the following operation which will construct the query to calculate the total and save you a lot of object instantiation and looping.

$transactionTotal = Transaction::groupBy('project_id')
            ->selectRaw('sum(total_amount) as raised')
            ->where('project_id', '=', $projectId)
            ->pluck('raised');

 $raisedAmount = $transactionTotal->first();