Search code examples
laravel-9accessormutators

Laravel 9 accessors and mutators - Simple example not working


So I am trying to get my mutators and accessors to work in Laravel 9, in my Tag model I have the following:

protected function name(): Attribute
{
    return Attribute::make(
        get: fn ($value) => strtolower($value),
        set: fn ($value) => strtolower($value),
    );
}

When displaying the name in my blade view however, the name is not being displayed in lower cases ({{ $tag->name }}), also not when saving a new model to the database.

The following does work btw:

public function getNameAttribute($value)
{
    return strtolower($value);
}

Also when using public it does not work:

public function name(): Attribute

Just trying to understand what I am doing wrong here?

I am using Laravel version 9.44


Solution

  • I dont know if the question's content is exactly your code. I had a similiar problem, get and set not working. But it worked in other model files.

    I just found the solution once again, ya, once again.

    If the attribute(column name) has two words, you have to make it together, first word should be lowercase.

    short_name

    protected function shortName(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => strtolower($value),
            set: fn ($value) => strtolower($value),
        );
    }