Search code examples
phplaravelgetsum

get() + sum() in one line laravel


My data

invoice|amount|
0001   | 10000|
0001   | 10000|

Now my code on Controller;

$invoices = Invoice::where('user_id', 1)
    ->where('status', 'Paid')
    ->orderBy('datePaid', 'desc')
    ->groupBy('no_invoice')
    ->get()
    ->sum('amount');  return view('invoice', ['invoices' => $invoices]);

I want show all data with get() and sum only field amount like this on my foreach.

invoice|total amount|
0001   | 20000|

Solution

  • You can use selectRaw in your select in query and then use sum(amount) like this

    $invoices = Invoice::selectRaw('*, sum(amount) as total')
        ->where('user_id', 1)
        ->where('status', 'Paid')
        ->orderBy('datePaid', 'desc')
        ->groupBy('no_invoice')
        ->get();
    

    Now you can print

    foreach($invoices as $invoice){
         echo $invoice->total
    }