Accessors and Mutators in Laravel
Accessors and Mutators are basically used to reduce the length of the code and supports the DRY (do not repeat yourself) principles.
Accessors
As the name suggests, it is used while accessing something and here something is the attributes (columns in the database) of a model.
Accessor in laravel transforms an Eloquent attribute value that is been accessed. To create an accessor, there is a method named get{AttributeName}Attribute which returns the expected thing that you want when you access the attribute.
e.g. If in your database, there is a field of first_name, second_name and you want to get the full name, you can create a accessor in the model like this:
public function getFullNameAttribute(){ return $this->first_name . ' ' . $this->last_name;}
You can access the “full_name ” attribute anywhere in your project like this:
$user = User::find(1);$name = $user->full_name;
Remember, the get{AttributeName}Attribute method should always be written like this in the “studly” case.
Mutators
As the name suggests, they are used to mutate something i.e. they are used to change the attribute before saving to the database.
Mutator in laravel transforms Eloquent attribute value when it is being set. To create a mutator, there is a method available in the model named set{AttributeName}Attribute. Whenever the field is being set anywhere it will come through this function and then go to the database.
e.g. If you want to save the capitalize name of user in the database, rather than applying the logic in controller you can create a mutator like this:
public function setNameAttribute($value){
$this->attributes['name'] = strtoupper($value);}
This function will be called whenever you interact with the attribute.
$user = User::find(1);$user->name = "abc";
The name “ABC” will be saved in the database.
If you want to read more about accessor and mutator , do have a look here:
You will find all the code related to accessor and mutator here:
If you like the blog, please hit that clap icon and if you want to read more such blogs, do follow me up.