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.
Connect with KoderSolution 🚀
Master modern software engineering, scalable architectures, and advanced backend systems.
Read more architectural deep-dives, systems tutorials, and engineering guides on kodersolution.com.
Subscribe to @kodersolution for concise, animated system design breakdowns and technical shorts.
Follow our official page for daily development tips, architecture discussions, and community updates.
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.