Accessors and mutators allow you to format Eloquent attribute values when retrieving and setting them.
Accessor
An accessor allows you to format an Eloquent attribute value when you retrieve it.
class User extends Model
{
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
}
// Usage
$user = User::find(1);
echo $user->full_name;
Mutator
A mutator allows you to format an Eloquent attribute value when you set it.
class User extends Model
{
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
}
// Usage
$user = new User();
$user->first_name = 'JOHN';
echo $user->first_name; // Outputs 'john'
These are powerful tools to ensure your data is always formatted correctly when interacting with your models.
Top comments (0)