Laravel Select with Sum Query Example

By Hardik Savani November 5, 2023 Category : Laravel

We mostly required to get sum of amount, salary etc in laravel. We can also get sum of column using mysql SUM(). We have two way to get sum of column value. first we can use laravel sum() of query builder and another one we can use with directly with select statement using DB::raw(). I give you both example you can see and use any one as perfect for you.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\UserProduct;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$userId = 1;

$amount = UserProduct::where('user_id', $userId)->sum('amount');

dd($amount);

}

}

Example 2:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Click;

use DB;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$data = Click::->select(DB::raw("SUM(numberofclick) as count"))

->orderBy("created_at")

->groupBy(DB::raw("year(created_at)"))

->get();

dd($data);

}

}

I hope it can help you...

Tags :
Shares