Home  >  Article  >  Backend Development  >  How to Calculate the Sum of Multiple Columns Using Eloquent

How to Calculate the Sum of Multiple Columns Using Eloquent

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 16:08:29941browse

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');

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

Read More

The above is the detailed content of How to Calculate the Sum of Multiple Columns Using Eloquent. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn