Laravel Collection Sum Column Example

By Hardik Savani April 16, 2024 Category : Laravel

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...

Shares