How To Select With Sum Query In Laravel With An Example

Hello there, Geek. In Laravel, we mostly needed to get sums of money, salaries, and so on. We can also get the column sum using mysql SUM (). We have two options for calculating the sum of column values. First, we can use the query builder’s sum() function, and then we can use it directly with a select statement using DB::raw (). I’ve given you both examples so you can choose which one is best for you.

FIRST EXAMPLE

<?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);
    }
}

SECOND EXAMPLE

<?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);
    }
}

All the best nerd!

Leave a Reply