DEV Community

Cover image for New way to define accessors and mutators in Laravel!
Reza Khademi
Reza Khademi

Posted on • Updated on

New way to define accessors and mutators in Laravel!

As you know there is a way to define accessor and mutator in laravel like below.

For example if we are in user model (App\Models\User):

For 'first name' Getter

 public function getFirstNameAttribute($value)
 {
        return ucfirst($value);
 }
Enter fullscreen mode Exit fullscreen mode
For 'first name' Settter

 public function setFirstNameAttribute($value)
 {
        $this->attribute['first_name'] = strtolower($value);
 }
Enter fullscreen mode Exit fullscreen mode

There is a new way to achieve this scenario But I must say Taylor Otwell actually mentioned it and it is quite useful and nice.

You can define both setter and getter in one single method like below:


public function firstName() :Attribute
{
    return new Attribute (
        get: fn($value, $attributes) => $attribute['first_name'],
        set: fn($value) => 'first_name' => $value
    );
}

Enter fullscreen mode Exit fullscreen mode

and that would do it as another way to define accessors and mutators both in one attribute function. If don't want to write any of these you can simply pass a null value for get/set.

Lets see two more examples for user model to cracked it down:

 public function fullName() :Attribute
 {
        return new Attribute(
            get: fn($value, $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
            set: function($value) {
                [$firstName, $lastName] = explode(" ", $value);

                return [
                    'first_name' => $firstName,
                    'last_name' => $lastName
                ];
            }
        );
   }

    public function password() :Attribute
    {
        return new Attribute(
            get: null,
            set: fn($value) => bcrypt($value)
        );
    }
Enter fullscreen mode Exit fullscreen mode

That's it... any questions?

Top comments (0)