Home > database >  Laravel: How to calculate sum of column values using eloquent?
Laravel: How to calculate sum of column values using eloquent?

Time:06-20

I'm trying to use sum() get the sum of column value, but unfortunately it isn't working and I can't figure out where I am wrong.

$total = Invoice::where('status', 'Completed')
             ->sum('amount');

This returns error Call to a member function first() on string

invoices (Table)

id code status amount
1 000001 Completed 300.00
2 000002 Completed 500.00
3 000003 Pending 100.00

I want to display the sum of invoices' amount in the view.

Blade View

Activity Count Total Amount
Invoices 6 900.00

CodePudding user response:

try this:

$total = Invoice::select(
DB::raw(SUM(amount) as total_amount)
)->where('status', 'Completed')->pluck('total_amount');

and foreach the value in the view file like:

@foreach(total as total_value)
<td>{{total_value}}</td>
@endforeach

CodePudding user response:

convert the `amount` attribute into Int before storing into database.for example 
$amount = $request->amount;
$invoice = new Invoice();
$invoice->amount = (int)$amount;
--
--
--
$invoice->save();

then you can use the above query for column sum

  • Related