Laravel

How to override Eloquent Mutators methods

Max Hutschenreiter -

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.
Invoice::create([
    'value' => $this->InvoiceService->getValue()
]);
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.

Read more in the official Laravel documentation.

Tags: Laravel · Eloquent · Mutators

Want products news and updates?

Sign up for our newsletter to stay up to date.

We care about the protection of your data. Read our Privacy Policy.

Impressions from our Team

  • #Office #Garden - #

  • #workhard - #

  • #belgrade #skyline - #

  • #happybirthday Phil :) - #

  • #happybirthday Stefan 🥂 - #

  • #happybirthday Lidija 🍾 - #

  • Say hi 👋 to our newest team member ☕️ - #

  • #bithday #cake 😻 - #

  • #stayathome #homeoffice #42coders - #

  • #stayathome #homeoffice #42coders #starwars :) - #

  • #stayathome #homeoffice #42coders - #

  • We had a really nice time with #laracononline #laravel - #

  • Happy Birthday 🎂 Miloš - #

  • Happy Birthday 🎂Nikola - #

  • #42coders #christmas #dinner what a nice evening :) - #

  • Happy Birthday 🎂 Ognjen - #

  • Wish you all a merry Christmas 🎄🎁 - #

  • #happybirthday Luka! - #

  • https://communian.com Triff dich mit Menschen aus deiner Umgebung die deine Interessen teilen :) Wir sind gerade live gegangen und freuen uns über jede neue Community die zu uns kommt ❤️ - #

  • Nice #meetup at #myposter thanks! - #

© 2020 42coders All rights reserved.