Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

unknownUser17's avatar

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

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***    |
0 likes
5 replies
aleahy's avatar

Although it's not in the code block you posted, you have called first() on the result of sum('amount').

2 likes
muathye's avatar
muathye
Best Answer
Level 41

Here is it.

$data = [];
$data['Total Amount'] = Invoice::where('status', 'Completed')->sum('amount');
$data['Count'] = Invoice::where('status', 'Completed')->count();
$data['Activity'] = 'Invoices';

You can call it in your view blade as following

{{$data['Total Amount']}}
{{$data['Count']}}
{{$data['Activity']}}
7 likes
vincent15000's avatar

sum()can be applyed on collections and not on queries.

First you have to retrieve your collection.

$invoices = Invoice::where('status', 'Completed')->get();

Then you can sum on the amount.

$total = $invoices->sum('amount');

Finally you have to pass the $total variable to the view.

return view('yourview', ['total' => $total]);

And you are able to display the total in blade.

Total : {{ $total }}
8 likes
Muajjam-imu's avatar

$query = YourModel::query(); $query->withCount([ 'activity AS yoursum' => function ($query) { $query->select(DB::raw("SUM(amount) as doneAmount"))->where('status', 'Completed'); } ]);

2 likes
shmshihan's avatar

$total = Invoice::whereIn('status', ['Completed','Pending'])->sum('amount');

Please or to participate in this conversation.