Eloquent ORM: Accessor and Mutator
Akshay Joshi

Akshay Joshi @doozieakshay

About: Goa-born IT grad in Bangalore, quirky tech co-founder of DoozieSoft (2013). Embraces hakuna matata, believes money follows effort. Devoted dad of two, balancing code and family life. Memento vivere.

Location:
Bangalore, India
Joined:
Jun 14, 2020

Eloquent ORM: Accessor and Mutator

Publish Date: Aug 3 '24
0 0

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.

Comments 0 total

    Add comment