DEV Community

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

Posted on

1

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

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay