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

peterdickins's avatar

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?

0 likes
4 replies
tykus's avatar

Use Eloquent API Resources to define the structure of your API response payload rather than relying on the Model itself

peterdickins's avatar

@tykus thank you, this is my CategoryResoure, how can I format the product.price field?

class CategoryResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'products' => $this->products
        ];
    }
}
jaseofspades88's avatar

@peterdickins I would recommend you create a ProductResource class and then you can do something like this:

return [
    'products' => ProductResource::collection($this->whenLoaded('products')),
];

...and then you could do the formatting for the Product on the ProductResource class. whenLoaded is a conditional function and if you just wanted to load the products in each time, do this:

return [
    'products' => ProductResource::collection($this->products),
];
1 like
tykus's avatar

@peterdickins the Product is a Resource in its own right. You would define a separate structure rather than passing the products Collection from the Category model.

Check out the documentation for handling nested resources

Please or to participate in this conversation.