Laravel Collection Sum Column Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Hello Brother, 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 lesson of sum values in collection laravel.

let's see simple lessons of sum() with collection and eloquent in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7 and laravel 8 application. so let's see bellow lesson that will helps you lot.

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

}

}

Result:-

1365

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

}

}

Result:-

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

)

)

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

}

}

Result:-

21

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

}

}

Result:-

1331

thank you very much for following up with me.

Recent Posts

Related Posts