In my model I have total price calculation based on hasMany relationship. It looks like this:
public function totalPrice(): string
{
return num_format($this->hasMany(Direction::class)->sum('price'));
}
I use num_format function which is described in helper.php file. In case I need to change number formatting I can always edit helper function. But I wonder if there be a better/nicer way to do this? As far as I understand I can't use $casts for function in this situation? What are your thoughts? Do you think apporach I'm using is correct? Thank you for your thoughts
CodePudding user response:
I think this is fine, I personally would decouple the relation, then have totalPrice be num_format($this->directions()->sum('price'))
If you wanted a global way of defining this, you can define a global scope which would be called something like sumWithDp
and then in any model with a defined relation you can call:
$this->relation()->sumWithDp('price', $decimalPlaces)
(or just always have it be 2 DP if you wanted)