ACCESSORS AND MUTATORS IN LARAVEL 5

What are ACCESSORS AND MUTATORS

Accessors and Mutators are custom user defined methods in Laravel. Accessors allow you format Eloquent attributes at time of retrieving that table attribute or column value, while mutators allow yoo format the attributes before saving them to the database.

Defining an Accessors in Laravel

All Accessors methods name in Laravel start with “get” keyword and ends with “attribute” keyword and in between the there is name of the attribute that you want too modify at time of retriving attribute.
To understand let take an example, suppose the attribute that you want to modify is first_name then your accessors name will be getFirstNameAttribute.

Example Usage:

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

Defining an Mutator in Laravel

All Mutator methods name in Laravel start with “set” keyword and ends with “attribute” keyword and in between the there is name of the attribute that you want to set at time of saving data in databse.
To understand let take an example, suppose the attribute that you want to set is first_name then your accessors name will be setFirstNameAttribute.

Example Usage:

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

Leave a Reply

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