Laravel Select with Sum Query Example
We mostly required to get sum of amount, salary etc in laravel. We can also get sum of column using mysql SUM(). We have two way to get sum of column value. first we can use laravel sum() of query builder and another one we can use with directly with select statement using DB::raw(). I give you both example you can see and use any one as perfect for you.
Example 1:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\UserProduct;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$userId = 1;
$amount = UserProduct::where('user_id', $userId)->sum('amount');
dd($amount);
}
}
Example 2:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Click;
use DB;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$data = Click::->select(DB::raw("SUM(numberofclick) as count"))
->orderBy("created_at")
->groupBy(DB::raw("year(created_at)"))
->get();
dd($data);
}
}
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Search Case Insensitive Query Example
- Laravel Eloquent selectRaw() Query Example
- Laravel Eloquent orderByRaw() Query Example
- Laravel Eloquent Where Query Examples
- Laravel Eloquent orWhere() Condition Example
- Laravel Eloquent WhereIn Query Example
- How to use Union Query with Laravel Eloquent?
- How to Get Query Strings Value in Laravel?
- Laravel Query Builder Where Exists Example
- Example of unionAll in Query Builder Laravel
- Laravel Join with Subquery in Query Builder Example