Laravel Sum Query with Where Condition Example

By Hardik Savani November 5, 2023 Category : Laravel

Hello,

In this tute, we will discuss laravel sum query with where condition. step by step explain laravel where sum greater than. I explained simply about laravel having sum query. let's discuss about laravel query where sum.

When ever you need to sum of column and require to get only those records has greater than some value in laravel query builder, then i will give you simple example how to use where condition with sum. you can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 version.

let's see bellow example:

Example 1: using having()

Controller Code:

<?php

namespace App\Http\Controllers;

use App\Models\User;

use DB;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$users = UserPayment::select("*", DB::raw('SUM(amount) as total'))

->groupBy("user_id")

->having('total', '>', 50)

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[user_id] => 1

[amount] => 56

[payment_date] => 2021-08-04

[status] => 1

[created_at] =>

[updated_at] =>

[total] => 56

)

[1] => Array

(

[id] => 2

[user_id] => 2

[amount] => 45

[payment_date] => 2021-09-07

[status] => 0

[created_at] =>

[updated_at] =>

[total] => 55

)

[2] => Array

(

[id] => 5

[user_id] => 5

[amount] => 66

[payment_date] => 2022-01-04

[status] => 1

[created_at] =>

[updated_at] =>

[total] => 66

)

)

Example 2: using havingRaw()

Controller Code:

<?php

namespace App\Http\Controllers;

use App\Models\User;

use DB;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$users = UserPayment::select("*", DB::raw('SUM(amount) as total'))

->groupBy("user_id")

->havingRaw('total > 50')

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[user_id] => 1

[amount] => 56

[payment_date] => 2021-08-04

[status] => 1

[created_at] =>

[updated_at] =>

[total] => 56

)

[1] => Array

(

[id] => 2

[user_id] => 2

[amount] => 45

[payment_date] => 2021-09-07

[status] => 0

[created_at] =>

[updated_at] =>

[total] => 55

)

[2] => Array

(

[id] => 5

[user_id] => 5

[amount] => 66

[payment_date] => 2022-01-04

[status] => 1

[created_at] =>

[updated_at] =>

[total] => 66

)

)

i hope it can help you...

Tags :
Shares