How to get sum of values by grouping using laravel?

by dalton_moen , in category: PHP Frameworks , a year ago

How to get sum of values by grouping using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a year 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.

Related Threads:

How to get the values using session in codeigniter?
How to use group by to sum values in mysql?
How to get values of checkbox array in laravel?
How to assign groups based on sum of values in oracle?
How to select / get values from database in laravel?
How to get nested key values in laravel?