Laravel 5: Eloquent – accessors & mutators

Eloquent: accessors & mutators

Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances.
For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

Accessors

Say, you have a table users and a model User that works with it.
You can easily access all columns from that table, e.g. by using auth()->user()->somecolumn.

But lets say, you want to attach some additional data to your User model from different models, e.g. from Model UserAddress, so you can access it easily using auth()->user().

Then you have to create in model UserAddress a method, that will push additional column to your User model.

Follow strict rules while creating method name.

There are 3 pieces that create method name:

  1. piece one: word ‘get
  2. piece two: name your property (attribute), how you want to access your dynamic value starting with Capital letter –
    e.g. ‘City‘, if you want to access it as auth()->user()->city
  3. piece three: word ‘Attribute

So, as a result, we get this name: getCityAttribute.

Now lets see that method.

Note argument $value .
Laravel will use it to inject into method appropriate value fetched from database table, so you can do your intended magic with it and return it, so you can access it somewhere (e.g. in Controller) in your project, like this:

That is all, there is to it.

Of course, this simple example just shows simple application, but many interesting things can be done using it.

Also, read about similar functionality here and here.
 Mutators
Defining A Mutator

Rule is very simple and very similar to that of Accessor.
It is because Accessor is similar to Mutator.

Difference is this:

  • Accessor: pulls data from database and allows to work on it in your code
  • Mutator: takes data you attach to column name, transform it to your likings (mutates it – hence mutator) and attach it to $attributes array for further action, e.g. updating its value in database

You create Mutator method in model, that allows you to access desired column in desired table.

How to create method name.
Same as in Accessor’s case, you have to follow structural rules.

There are 3 pieces that create method name:

  1. piece one: word ‘set
  2. piece two: name of column in database table you want to access starting with Capital letter
    e.g. ‘Username‘, for table column name ‘username
  3. piece three: word ‘Attribute

So, as a result, we get this name: setUsernameAttribute.

Now lets see that method.

And this how you may use it, e.g. in a Controller:

Date Mutators
tell Laravel which columns are dates

By default, Eloquent will convert (mutate) the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class to provide an assortment of helpful methods.You can define more columns as dates.
Here is how:

Read more here.

tell Laravel, how you wish to format date columns on tables processed by Model

By default, timestamps are formatted as ‘Y-m-d H:i:s‘.
If you need to customize the timestamp format, set the $dateFormat property on your model.
This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON

Read more here.

Usage

Now we can save date in proper format to database:

… or access using one of multitude useful Carbon methods:

Attribute Casting

The $casts property on your model provides a convenient method of converting attributes to common data types.
So, you can cast data from given column to bool, even if it is stored as 0/1.

Important:
This casting works upward, meaning it will mutate/cast data into selected format, when it comes FROM server.
So, it is useless for inserting/updating data.

Since PDO is responsible for testing data, many people do not bother. But old-times like me like to cast data downward (to server), so data send for storage in database, or even for processing is in expected format.
Attribute casting will not help us here.

The supported cast types are:
integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.

Sample use:

Read more here.

Array & JSON Casting

I am stealing below text from Laravel docs – as there is just no better way to put it.

The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model.

In other words, if have serialized JSON stored in field, casting that field to array will get that serialized JSON and serialize it to array, so you start using data right away without doing it over and over by hand, e.g.:

… allows to use ‘options’ data right away – be it access, or storage: