So let’s say I have model Product
with getPriceAttribute
accessor like this
public function getPriceAttribute()
{
return number_format($this->price);
}
So on every response, I will get price with formatted number. But in some case, I need to return the unformatted number. Example:
$product = Product::find(1);
$product->price = preg_replace('/[^0-9]/', '', $product->price);
But the result still gives me the formatted number instead of unformatted number.
I know I can create separate accessor attribute like getUnformattedPriceAttribute
for unformatted number, but the client need to receive the same price
attribute.
And the work around that I do for now is to convert the model into array first using ->toArray()
and then set the key price
to unformatted one. But I want to know if It is possible to override this accessor behaviour when It is still in Laravel Model.
Thank you!
2
Answers
As Brombeer mentioned, it’s better -IMO- to keep the original columns as is, and add a new mutator/accessor to your model with the formatted text with the new name, you can also add the new name to the
$appends
array to automatically add it to your model. However, to answer your original question, you can always use aliases when retrieving the model, this will revert the accessor operation:In Laravel, the accessors are designed to return formatted values whenever the corresponding attribute is accessed. However, if you need to retrieve the unformatted value in some cases, you can indeed implement a workaround.
As you mentioned, creating a separate accessor for the unformatted price is one approach. However, if you need to maintain the same attribute name for both formatted and unformatted prices, you can utilize a combination of accessors and dynamic properties