How to get sum of values by grouping using laravel?

by dalton_moen , in category: PHP Frameworks , 4 days ago

How to get sum of values by grouping using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 days ago

@dalton_moen 

To get the sum of values by grouping in Laravel, you can use the groupBy and sum methods provided by Eloquent. Here's an example of how you can achieve this:

1
2
3
4
5
6
7
$sums = YourModel::select('group_column', DB::raw('sum(value_column) as total'))
            ->groupBy('group_column')
            ->get();

foreach ($sums as $sum) {
    echo "Group: " . $sum->group_column . ", Total: " . $sum->total;
}


In this example, replace YourModel with the name of your Eloquent model, group_column with the column you want to group by, and value_column with the column you want to sum. This code will group the values based on the specified column and calculate the sum of the values for each group.