Accessor and Mutators in Laravel

|
| By Webner

Accessor and Mutators are allowed to alter the data before saving and fetching from the database. An accessor is used to change the format while fetching the data from the database and mutators set the format attributes before retrieving the data from the database.

Why do we need this?

In core language, if data is saved in some format in the database, but we need to display the data in another format then we need functions to change the format.

Accessor

Accessor is used to define the column name in the function for example, first_name is a column, use the getFirstNameAttribute();. Be sure the name should be in a capital case.

Syntax: getFirstNameAttribute()
Class User extends Modal {
public function getFirstNameAttribute($value){
return ufirst($value);
}
}

In the example ufirst() change the first name character into upper case and return from the Modal.

$user = \App\User::find(1);
$first_name = $user->first_name;

Mutators

To define mutators set the attributes using setFristNameAttributes().

Syantx: setFirstNameAttribute()
Class User extends Modal{
public function setFirstNameAttribute($value){
$this->attribute[‘first_name’] = strtolower($value);
}
}

The mutators will fetch the value of the first name and are being set on the attribute and allow to change the data on Eloquent Modal internal Attribute property.

$user = \App\User::find(1);
$user->first_name = ”ABC”;

In this example Now setFirstNameAttribute() called with the First Name is ABC.

Leave a Reply

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