Accessors and mutators in Laravel

A common issue when building a webapplication is the case where you want to display variables in a different format than they are stored in your database. For example, dates are by default stored as yyyy-mm-dd, but in the Netherlands dates are written as dd-mm-yyyy. Or maybe you stored the names of your users in lowercase, but you would like to show them with a capital. For those kind of situations, the accessors and mutators of Laravel are of great use.

Accessors

An accessor is a method that will modify a value when you retrieve it from your database. The method should be placed in the model that corresponds to the database table. Let’s illustrate this with an example from a webapplication in which parents keep track of the length and width of their children. The details of each child are stored in a database table ‘kids’ and the corresponding model is ‘Kid’.

Now we would like to retrieve the date of birth of the kid, which is stored in the column ‘date_of_birth’ of type ‘date’ (yyyy-mm-dd). As we are situated in the Netherlands, we would like to retrieve this date and display it as dd-mm-yyyy. This can be achieved by adding the following method to the Kid model:

public function getDateOfBirthAttribute($value)
{
    return Carbon\Carbon::createFromFormat('Y-m-d', $value)->format('d-m-Y');
}

The name of the method is important here because it tells Laravel we are dealing with an accessor. It consists of three parts. The first part is ‘get’, indicating you define an accessor and you want to apply this function when retrieving data from the database. The second part is the name of the database column in camelcase. Here, the name of the column is ‘date_of_birth’, so this would be ‘DateOfBirth’. The third part is ‘Attribute’.

Within this method, you may write any logic you like. In this example we keep it simple and only change the format to ‘dd-mm-yyyy’.

Mutators

Mutators will do the opposite of accessors: they modify a value before saving it to your database. In our webapplication, we use a mutator when a parent registers a new child in the application. We want to allow them to enter the date of birth in the Dutch format (dd-mm-yyyy), but it has to be stored as yyyy-mm-dd. This can be achieved by adding the following method to the Kid model:

public function setDateOfBirthAttribute($value)
{
   $date = Carbon::createFromFormat('d-m-Y',$value);

   $this->attributes['date_of_birth'] = $date->format('Y-m-d');
}

Again, the name of the method is important. It consists of the same three parts as the name of an accessor, except that it start with ‘set’ to indicate that it is a mutator. Within the method, you may write any logic you like, but don’t forget to add your modified value to the attributes:

$this->attributes[‘date_of_birth’] = ‘the new value’

Summary

Accessors and mutators are very powerful methods for modification of database values when you retrieve or store them. However, you should keep in mind that these modifications will be applied each time you retrieve or store a value. This means that when you add them to an existing application, you have to check all code to make sure everything still works correctly. Some of your old code may expect certain values to be in the old format. It’s therefore best to add accessors and mutators to the models at the start of a new project.


Mijn Twitter profiel Mijn Facebook profiel
Leonie Derendorp Webdeveloper and co-owner of PLint-sites in Sittard, The Netherlands. I love to create complex webapplications using Laravel! All posts
View all posts by Leonie Derendorp

Leave a Reply

Your email address will not be published. Required fields are marked *