Mutators and Accessors in Laravel

In this article, we’ll go through mutators and accessors of the Eloquent ORM in the Laravel web framework. After the introduction, we’ll go through a handful of examples to understand these concepts.

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.
Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. In Laravel, mutators and accessors allow you to alter data before it’s saved to and fetched from a database. To be specific, the mutator allows you to alter data before it’s saved to a database. On the other hand, the accessor allows you to alter data after it’s fetched from a database.

How to define an Accessor ?

The syntax used for defining an Accessor is very simple, getFullNameAttribute(). Here FullName is the “studly” cased name of the column you wish to access.
In this example, we’ll define an accessor for the first_name and last_name attributes. The accessor will automatically be called by Eloquent when attempting to retrieve the combine value of the first_name and last_name attribute.
Suppose we have two fields in our table for our users : first_name and last_name. And though these two fields can be used when needed, but sometimes we need these two combined to show the full name as a single field, have operations on them as a whole.

class User extends Model
{
/**
* Get the user's full name.
*/
public function getFullNameAttribute()
{
return $this->first_name . " " . $this->last_name;
}
/**
* It will return user's first_name in Uppercase
*/
public function getFirstNameAttribute()
{
return strtoupper($this->first_name);
}
}

So what’s happening here is, we have created a function which will get called every time full_name is called on the user( Model ). There is a pattern, if you see closely, in every attribute function you make. The get[attribute_name]Attribute(), is the way you can create an accessor.

But there is a catch, you can not use this attribute name in eloquent queries like any other fields, you can only use this attribute when you have the collection, but not on the eloquent queries as you might know, the eloquent queries work on the database fields, and our attribute comes in the scene, after we have all the fields of the table.

For example,

$users = User::orderBy('full_name')->get();

The above code would not work.
But,

$users = User::all()->sortBy('full_name');

The above would work as sortBy() requires a collection to work on. So after getting the collection of users, we can then sort it by using sortBy()function.

Note: There is a sortByDesc() that would sort the collection by descending order.

How to define a Mutator ?

If you have worked with any OOP language, you would be familiar with getter and setter methods. So, the accessors are the getter and mutators are the setter method.

To define a mutator, define a setFirstNameAttribute method on your model where First Name 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.

/**
* Set the user's first name in lower case.
*/
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}

And can be used like this :

$user->first_name = 'NIKUNJ';
$user->save();

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.

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.

If you have any query or suggestions, feel free to ask me via the comment section below.

1 Comment

Leave a Reply