How to override Eloquent Mutators methods

money
Share on facebook
Share on twitter
Share on linkedin

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.

 

With 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 the way how to override defined the Mutator method and to store provided value as it is. The answer is simple, let’s use the “setRawAttributes” method. Here is an example.

 

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.

Read more in the official Laravel Documentation.

Subscribe to our newsletter

Be first to read new helpful post

Share this post with your friends

Share on linkedin
Share on xing
Share on twitter
Share on facebook

Communian – COMING SOON

We at 42coders love meetups and think that they are a valuable asset to the community. And we willingly attend to them. Not to mention

Leave a Reply

avatar
  Subscribe  
Notify of