Laravel Eloquent Sum Multiple Columns Example

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello Dev’s
Hope all are good. Today I will show you how to multiple columns in laravel eloquent. Are you looking for an good example of laravel eloquent sum multiple columns in database. So here you can see laravel query builder sum of two columns. Here I will explain simply about multiple sum by using laravel query. I will like to share with you a example multiple column sum in laravel. So let’s see bellow a short example of laravel sum query with multiple columns.

So let’s see a simple example of multiple fields sum in laravel application. Now you can easily use it with your any version of laravel 5, laravel 6, laravel 7 and laravel 8 applications. So let’s start and see bellow example that must helps you lot in your project.

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] => 4

            [name] => Apple

            [total_sell] =>21 

            [total_stock] => 3

        )

    [2] => Array

        (

            [id] => 5

            [name] => HP

            [total_sell] => 12

            [total_stock] => 20

        )

)

Read Also: How to check array is empty or null or undefined in javascript?

Hope it will help you. For more you can follow us on facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →