Laravel collections already have a sum method built in:
$this->Items->sum('price')
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Greetings,
I have a Invoice Model and it hasMany Items with Price attribute. I would like to sum all the Prices in Invoice. I have written public function on Invoice:
public function sum() {
$sum=0;
foreach($this->Items()->all() as $item) {
$sum += $item->price;
}
return $sum;
}
I would like to call this method and pass the value to the view. Would you recommend to add it to the Invoice Model or it should reside somewhere else? Is it possible to work with $this like that or do I have to use some Mutators or Scopes and access Model instance by ID without the possibility to use $this.
Your help is much appreciated. Thanks :)
Complex solution from @jakeryansmith: If this is just for presentation then a presenter is fine, but if you want to be able to use the summed value in other parts of your application then don't use a presenter.
Why not just create a service class for this? Then you can access it in many ways: in your controller, in a view with blade service injection, or in any other part of your app.
Easier solution from @sid405: It's a common issue that people hack all sorts of different way. That is the textbook case for a presenter.
On the other hand you could abstract that logic to a repository-like static class and call it from the view, but that just seems an utter overkill.
To my knowledge these are the options for your problem, because as you say, the scope solution is not for your case.
I installed it on a L5.1.11 project two days ago and it works fine and all the info is contained on the github page.
Frankly to use a view composer and service container just for this, seems a bit much. Overengineering it.
I usually use presenters for a multitude of 'bits and bobs' that are particular and need to 'just-work'.
I don't know what else to suggest you mate.
Please or to participate in this conversation.