In this article we will learn to use aggregate function sum in laravel eloquent and query builder. Laravel itself provide inbuilt method to sum
the columns like in MySQL or SQL based database we can do sum of columns using sum aggregate function.
Sum method will give you the sum of all rows in query by providing the column name. For example if you have 10 rows and you want the sum of a column X then you will get the sum of that column from 10 rows
Laravel eloquent or query builder sum
method do the same as aggregate function. Laravel sum accepts one parameter as column name.
Here is the syntax
Model::sum(COLUMN_NAME);
//or
Model::select(\DB::raw("SUM(COLUMN_NAME), other_columns "))->get(); // or first()
//or
\DB::table('table_name')->sum(COLUMN_NAME);
//or
\DB::table('table_name')->select(\DB::raw("SUM(COLUMN_NAME), other_columns "))->first()
In the above syntax we have used 4 examples to show all possibilities to use sum aggregate function.
First is using the Model and sum method of eloquent. Second is Model with select and Db::raw class.
In the third example we have used Query Builder DB class and table function to use sum method of it.
And final example is query builder with select and db raw to use sum method of MySQL or SQL.
Result of above query will be:
select SUM(column_name) from `table`
//OR
select SUM(column_name), other_columns from `table`
Let’s understand laravel sum in eloquent query with example
Example 1 – Laravel sum aggregate function query using eloquent sum method
So in this example i will use laravel query builder or eloquent sum method to do the sum of column.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Article = Article::sum('like_count');
\\or
DB::table('articles')->sum('like_count');
}
}
Output will be :
select sum(`like_count`) from `articles`
Example 2 – Laravel sum query using raw query
In this example i will use laravel query builder DB::raw
method with select to sum the column
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Article = Article::select(\DB::raw('sum(like_count), aticles.*'))->get();
\\or
$Article = Article::selectRaw( 'sum(like_count), aticles.*')->get();
\\OR
DB::table('articles')->select(\DB::raw('sum(like_count), aticles.*'))->first();
}
}
In the above example we have used articles table and created a model in our laravel application. Then we imported the necessary classes and used the sum method.
Output will be :
select sum(`like_count`), `aticles`.`*` from `articles`
Also Read : How to use laravel count rows with example ?