guratr's avatar
Level 7

Eloquent custom Accessor doesn't work on Laravel 11

I have a legacy project that has been upgrading from Laravel 6 days, and back then the standard way to define accessor was declaring getSomePropertyAttribute function, and as were said in the documentation

You may also use accessors to return new, computed values from existing attributes:

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

Now i'm upgrading from Laravel 10 to 11, and all custom accessors stop working. I tried redefining accessors in new format like this

protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => "Test Name",
        );
    }

But calling $model->full_name returns null. I even tried adding full_name to $appends property, and when calling ->toArray on the model, i see full_name, but it still null when called on the model. Everything works if the name of accessor corresponds to some existing attribute, but aliases do not work.

Anyone found the solution to this?

0 likes
3 replies
Sinnbeck's avatar

Can you share the full code of a model that does not work?

jj15's avatar

Does defining it like so work?

protected function fullName(): Attribute
{
    return Attribute::make(
        get: fn (mixed $value, array $attributes) => "{$attributes['first_name']} {$attributes['last_name']}",
    );
}

You'll notice that the closure is now receiving a second parameter, $attributes. This is needed if full_name isn't an actual column in your database (which is what $value would contain) and you want to build your accessor from multiple attributes since I don't believe the closure is being bound to $this.

tykus's avatar

@guratr did you ensure that you are aliasing the correct Attribute class .i.e.

use Illuminate\Database\Eloquent\Casts\Attribute;

Please or to participate in this conversation.