DEV Community

Cover image for Eloquent ORM: Accessor and Mutator
Akshay Joshi
Akshay Joshi

Posted on

Eloquent ORM: Accessor and Mutator

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;
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

These are powerful tools to ensure your data is always formatted correctly when interacting with your models.

Top comments (0)