Laravel DB raw with sum of column example

Avatar
C

Callum Davies

Senior Backend Engineer••
7627Views
5mRead
0Reactions

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.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles