Use Eloquent API Resources to define the structure of your API response payload rather than relying on the Model itself
Aug 23, 2023
4
Level 2
Override accessor
Hi,
I have an accessor method on my Product model to get prices for a product.
protected function getPriceAttribute(): float
{
if ($this->isForVendor()) {
return $this->getVendorPrice();
}
return $this->attributes['price'];
}
I need to pad the result by 2 decimal places in the api response. In order to do this I need to use the number_format function which returns a string. But I can't update this function as it's called in many other areas of my app and relies on the result being a float.
And I can't update the ProductResource class as this is being called from a related model; Category
Category::with('products')->get();
Is there another way to achieve this?
Please or to participate in this conversation.