The main point of this article is to explain how to override the mutator’s method defined in the model. But first, let me explain to you what are the Eloquent Mutators.
Let’s say that we have in our table a field named “value” that contains the money amount expressed in the base money unit – cents, therefore the field is defined as an integer data type.
But the Model gets money amount expressed as float type with two decimal points. In that case, we could create a Mutator method named setValueAttribute.
// $value = 1423.89 - value passed to the Model
public function setValueAttribute($value)
{
$this->attributes['value'] = $value * 100;
}
// $value = 142389 - value stored in the Database table
With a defined Mutator, every value amount passed to the Model will be converted into cents and stored in the Database as an integer data type.
More about Eloquent Mutators you can read in the official Laravel’s documentation https://laravel.com/docs/5.8/eloquent-mutators.
What if our application gets the new one service that returns money amount expressed in base money units – cents.
In that case, the stored value will be multiplied 100 times, therefore we have to find a way how to override defined the Mutator method and to store the provided value as it is. The answer is simple, let’s use the “setRawAttributes” method. Here is an example.
$invoice = new Invoice;
$invoice->setRawAttributes([
'value' => $this->InvoiceService->getValue()
]);
$invoice->save();
The value provided by the service will be stored in the Database table as it is, the Mutator method defined in the Model will be overridden.