Laravel accessors and mutators are basically custom user defined methods that allow you to format Eloquent attributes.


Accessors are used to format the attributes when you retrieve/fetch them from the database, whereas Mutators are used to format the attributes before storing them to the database.


Let's see how to define an Accessor:


Syntax for defining an accessor is getFooAttribute() where Foo is the capitalized attribute you want to access. For example, If your attribute is first_name and we want to make sure that first name will always be camel-cased when you fetch it from database, then we'll need to define an accessor as follows:

public function getFirstNameAttribute($value) {
    return ucfirst($value);
}

Above is one of the commonly used examples, but accessors can be used to format dates, prices, full names, etc.

Yes, you read it right! We can combine two attributes to create one by defining an accessor for it.

public function getFullNameAttribute(){
    return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}

And to use, you simply access it as if it exists as a column/field in the database:

$user = App\Employee::find(1);
echo $user->full_name;


Now let's see to how define a Mutator:


Syntax for defining a mutator function is setFooAttribute() where Foo is a camel cased column you want to access. But this time, we want to make change before saving it to the database. Taking the same example as above, to save first name as capitalized, we will define a mutator as follows:

public function setFirstNameAttribute($value) {
    $this->attributes['first_name'] = ucfirst($value);
}

Notice that we aren't returning anything because we are directly accessing and setting the attribute value. With this mutator, we are ensuring that first name will always be capitalized before storing it in database.


An excellent example of Mutator would be while saving passwords. Whenever we deal will passwords, we need to ensure that they are encrypted before storing them in database. So how would we define mutator for it:

public function setPasswordAttribute($value) {
    $this->attributes['password'] = Hash::make($value);
}


Hope this helped you and gave you a clear understanding about the powers of accessors and mutators in Laravel.


Happy Coding! :)