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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more