Laravel db raw with sum of column example

In this article, I will share with you, how to sum SQL raw query. Sometimes, we need to sum some columns using SQL select with raw query.

If you need to sum SQL columns using raw statements, you are most welcome to follow this post. That's start

 

1. Using DB Table

$data = DB::table("users")
	    ->select(DB::raw("SUM(sales.user_id) as total_sale"))
        ->leftjoin("sales","sales.user_id","=","users.id")
	    ->groupBy("users.id")
	    ->get();
dd($data);

2. Using Model

$data = User::query()
	    ->withCount('sales as total_sale', function($query){
            $query->select(DB::raw("SUM(amount)"));
        })->get();
dd($data);

 

I hope, you will find your solution. Thanks for reading our article.

Related Post

Maksud

Maksud

I am a thinker, not a talker.