Laravel Eloquent Sum Multiple Columns Example

By Hardik Savani March 19, 2021 Category : Laravel

Are you looking for an example of laravel eloquent sum multiple columns. you can see laravel query builder sum two columns. i explained simply about multiple sum in laravel query. i would like to share with you multiple column sum in laravel. Let's see bellow example laravel sum query multiple columns.

let's see simple examples of multiple fields sum 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 example that will helps you lot.

Example

<?php

namespace App\Http\Controllers;

use App\Models\Product;

use DB;

class SignaturePadController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$products = Product::select(

"id",

"name",

DB::raw("SUM(sell) as total_sell"),

DB::raw("SUM(stock) as total_stock")

)

->groupBy("category_id")

->get();

dd($products->toArray());

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Silver

[total_sell] => 40

[total_stock] => 139

)

[1] => Array

(

[id] => 49

[name] => Apple

[total_sell] =>

[total_stock] => 3

)

[2] => Array

(

[id] => 52

[name] => Dell

[total_sell] =>

[total_stock] => 2

)

)

I hope it can help you...