DEV Community

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

Posted on • Edited on

4 1

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?

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please drop a ❤️ or a friendly comment on this post if it resonated with you!

Okay