Laravel Collection Sum Column Example
Today, i would like to show you laravel collection sum column. you can understand a concept of laravel eloquent collection sum. I’m going to show you about laravel sum of column query. This article goes in detailed on laravel get sum of column value group by. So, let's follow few step to create example of sum values in collection laravel.
let's see simple examples of sum() with collection and eloquent in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application. so let's see bellow example that will helps you lot.
Example 1
<?php
namespace App\Http\Controllers;
use App\Models\Product;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$sum = Product::sum('price');
dd($sum);
}
}
Output:
1365
Example 2
<?php
namespace App\Http\Controllers;
use App\Models\Product;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$products = Product::select("id", "name", \DB::raw("SUM(price) as total"))
->groupBy("category_id")
->get();
dd($products);
}
}
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Laravel 8 Form Validation
[total] => 2497
)
[1] => Array
(
[id] => 49
[name] => Apple
[total] => 330
)
[2] => Array
(
[id] => 52
[name] => Dell
[total] => 410
)
)
Example 3
<?php
namespace App\Http\Controllers;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$sum = collect([1, 2, 3, 4, 5, 6])->sum();
dd($sum);
}
}
Output:
21
Example 4
<?php
namespace App\Http\Controllers;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$collection = collect([
['name' => 'Laravel', 'price' => 176],
['name' => 'PHP', 'price' => 1096],
['name' => 'Angular', 'price' => 59],
]);
$sum = $collection->sum('price');
dd($sum);
}
}
Output:
1331
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection keys() Method Example
- Laravel Collection isEmpty() and isNotEmpty() Method Example
- Laravel Collection Implode Method Example
- Laravel Collection Flip Method Example
- Laravel Collection Except() Method Example
- Laravel Collection diff(), diffAssoc() and diffKeys() Example
- Laravel Collection Push() and Put() Example
- Laravel Collection SortBy Tutorial with Examples
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Search Method Example