Search code examples
phplaravelaccessorlaravel-10

Laravel's 10 accessor doen't work without mentioning return type as :Attribute


protected function isPublished(): Attribute
{
    return Attribute::make(
        get: fn($value) => $value ? 'yes' : 'no',
    );
}

As we know that mentioning the return type as "Attribute" is not necessary until we don't use strict type so before mentioning the return type the accessor wasn't working but when I mentioned the return type it started working why even ?

It should work without mentioning the return type as :Attribute


Solution

  • according to the official documentation: All attribute accessor / mutator methods must declare a return type-hint of Illuminate\Database\Eloquent\Casts\Attribute:

    https://laravel.com/docs/10.x/eloquent-mutators#defining-an-accessor

    and that's all for it to work properly.