What is the use of Accessors and Mutators?
Laravel accessors and mutators are customs, user-defined methods that allow you to format Eloquent attributes. Accessors are used to format attributes when you retrieve them from the database.
1. Defining an accessor
The syntax of an accessor is where getNameAttribute()
Name is capitalized attribute you want to access.
public function getNameAttribute($value)
{
return ucfirst($value);
}
2. Defining a mutator
Mutators format the attributes before saving them to the database.
The syntax of a mutator function is where setNameAttribute()
Name is a camel-cased column you want to access. So, once again, let’s use our Name column, but this time we want to make a change before saving it to the database:
public function setNameAttribute($value)
{
$this->attributes['name'] = ucfirst($value);
}