Although it's not in the code block you posted, you have called first() on the result of sum('amount').
Jun 20, 2022
5
Level 1
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*** |
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
Please or to participate in this conversation.