Laravel 9 Eloquent Accessors and Mutators Example

Hello artisan,

Did you know that Laravel team improved Eloquent accessors / mutators. So in this accessors / mutators example tutorial, I will show that Laravel 9.x offers a new way to define Eloquent accessors and mutators.

So if you don't know what changes happen, then this tutorial is for you to know the new way to define Eloquent accessors and mutators. You know that In previous version like Laravel 5, 6 , 8 of Laravel, the only way to define accessors and mutators was by defining prefixed methods on your model like:

public function getNameAttribute($value)
    return strtoupper($value);
public function setNameAttribute($value)
    $this->attributes['name'] = $value;


Now we can do the same thing using one method in our model like:

use Illuminate\Database\Eloquent\Casts\Attribute;
public function name(): Attribute
    return new Attribute(
        get: fn ($value) => strtoupper($value),
        set: fn ($value) => $value,


Read also: Laravel 9 Custom Token Based Api Authentication Tutorial


Hope this Laravel 9 Eloquent Mutators and Accessors example will help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js