DEV Community

Cover image for How to Calculate the Sum of Multiple Columns Using Eloquent
Saddam Hossain
Saddam Hossain

Posted on

How to Calculate the Sum of Multiple Columns Using Eloquent

in this tutorials i will show you How to Calculate the Sum of Multiple Columns Using Eloquent. Laravel offers built-in support for aggregating column values through the ‘sum‘ method, allowing you to calculate the total of a column’s values. You Can learn How to Calculate the Average of a Column Using Eloquent

The main caveat here is that Eloquent can only sum one column at a time. To sum 2 columns we either call sum() twice and add them or we use DB::raw to explicitly make a SUM of both columns:

$product = 'PS5'

// Calculating `online_sales + in_store_sales` using ->sum()
$eloquentSum = Sale::where('product_name', $product)->sum('online_sales')
               + Sale::where('product_name', $product)->sum('in_store_sales');

// Calculating `online_sales + in_store_sales` using DB::raw('SUM(..)'
$rawSum = Sale::where('product_name', $product)
    ->select(DB::raw('SUM(online_sales + in_store_sales) as total_sales'))
    ->value('total_sales');
Enter fullscreen mode Exit fullscreen mode

In this post we’ll make a simple application with a migration and model, add some test records and finally demonstrate how to calculate the sum of 2 columns to print online_sales + in_store_sales of a specific product. I will include an example for both the method that uses Eloquent’s sum() as well as the method that uses DB:raw('SUM(..)).

Let’s get started! How to Calculate the Sum of Multiple Columns Using Eloquent
How to Calculate the Sum of Multiple Columns Using Eloquent
Step 1: Create a Laravel Project
Begin by creating a new Laravel project using the following commands in your terminal:

composer create-project laravel/laravel sum-columns-example
cd sum-columns-example
Enter fullscreen mode Exit fullscreen mode

Read More

Top comments (0)