Laravel Sum Query – i often need to get sum of total visitors, amount, salary etc in PHP laravel. get the sum of two different columns using Laravel query builder.
Laravel Sum Query with Where Condition
I can also get the total sum of column using mysql SUM() bellow Laravel Select with Sum Query Example.
Example 1: using having()
Laravel Controller Code:
<?php namespace App\Http\Controllers; use App\Models\Member; use DB; class PakaController extends Controller { /** * Write code on Method * created by Pakainfo.com * @return response() */ public function index() { $members = MemberSalary::select("*", DB::raw('SUM(rank) as total')) ->groupBy("member_id") ->having('total', '>', 50) ->get(); dd($members); } }
Result
Array ( [0] => Array ( [id] => 1 [member_id] => 1 [rank] => 56 [salary_date] => 2021-08-04 [is_active] => 1 [created_at] => [updated_at] => [total] => 56 ) [1] => Array ( [id] => 2 [member_id] => 2 [rank] => 45 [salary_date] => 2021-09-07 [is_active] => 0 [created_at] => [updated_at] => [total] => 55 ) [2] => Array ( [id] => 5 [member_id] => 5 [rank] => 66 [salary_date] => 2021-01-04 [is_active] => 1 [created_at] => [updated_at] => [total] => 66 ) )
Don’t miss : Sql Concatenate Two Columns in Laravel
Example 2: using havingRaw()
Laravel Controller Code:
<?php namespace App\Http\Controllers; use App\Models\Member; use DB; class PakaController extends Controller { /** * Write code on Method * created by Pakainfo.com * @return response() */ public function index() { $members = MemberSalary::select("*", DB::raw('SUM(rank) as total')) ->groupBy("member_id") ->havingRaw('total > 50') ->get(); dd($members); } }
Result
Array ( [0] => Array ( [id] => 1 [member_id] => 1 [rank] => 56 [salary_date] => 2021-08-04 [is_active] => 1 [created_at] => [updated_at] => [total] => 56 ) [1] => Array ( [id] => 2 [member_id] => 2 [rank] => 45 [salary_date] => 2021-09-07 [is_active] => 0 [created_at] => [updated_at] => [total] => 55 ) [2] => Array ( [id] => 5 [member_id] => 5 [rank] => 66 [salary_date] => 2021-01-04 [is_active] => 1 [created_at] => [updated_at] => [total] => 66 ) )
I hope you get an idea about laravel sum query.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.