Start a Project

What are Accessors and Mutators in Laravel and how to use them ?

What are they ?

In order to format the Eloquent Attributes Accessors and Mutators are used. Laravel Accessors and Mutators are custom, user defined methods.

Accessors are used to format the attributes when you retrieve them from database.
Whereas, Mutators are used to format the attributes before saving them into the database.

How to define an Accessor ?

The syntax used for defining an Accessor is very simple,  getFooAttribute(). Here Foo is the “studly” cased name of the column you wish to access.

Let’s take an example. In this example, we’ll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute:

As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may access the first_name attribute on a model instance:

Accessor can also be used to return new, computed values from existing attributes:

How to define a Mutator ?

To define a mutator, define a setFooAttribute method on your model where Foo is the “studly” cased name of the column you wish to access. So, again, let’s define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model’s internal $attributes property. So, for example, if we attempt to set the first_name attribute to Sally:

In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its resulting value in the internal $attributes array.

What are Date Mutators ?

By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods. You may add additional date attributes by setting the $dates property of your model:

You may disable the default created_at and updated_at timestamps by setting the public $timestamps property of your model to false.

When a column is considered a date, you may set its value to a UNIX timestamp, date string (y-m-d), date-time string, or a DateTime/ Carbon instance. The date’s value will be correctly converted and stored in your database:

Conclusion

I really hope that I helped you understand what accessors and mutattors are, and if you don’t already use them I hope you now have an idea for what you can use them in your projects.

Source: Laravel

Exit mobile version