Accessors and Mutators in Laravel

By Michael Williams, Published on 04/23/2018

In Laravel, Accessors and Mutators allow you to format attributes when they are retrieved or when they are set on your models.

The beauty in Accessors and Mutators is that, once defined. The behavior you specify, will always be associated with those fields.

Defining An Accessor:

Lets assume that you have a Users model with a last_visit_date column. You would create the following method studly cased.

public function getLastVisitDatetAttribute($date) { return Carbon::createFromFormat('Y-m-d H:i:s', $date)->diffForHumans(); }

From there, whenever you access last_visit_date, it will always be returned as "5 days ago" rather than 2018-04-14 00:00:10.

Defining A Mutator:

Similar to an Accessor. A Mutator is created in studly case. Assuming in the same Users model there was a password field.

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

Now, whenever a password is entered. It will automatically be hashed before it is saved in the database.

These are just a couple things you can do. You can go to the Laravel site to read more about Accessors and Mutators