Search code examples
phplaravelaccessor

laravel model accessors not working in laravel 5.8


the attribute (full name in this instance) does not show up when using User::find(1); (which actually returns an user instance) and dd("test") inside the accessor is also not called

i've dd'd the model using tinker and i've tried using dd on the $request->user() output returns the same.

class User extends Authenticatable
{
    use Notifiable,HasApiTokens;


    protected $hidden = [
       'id',
        'master_password',
        'remember_token',
        'provider',
        'provider_id',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    public function getFullNameAttribute()
    {
        dd("test");
        return "test";
    }

}

i expect the user attribute with the field full_name returning "test". (or a dump and die if you let the dd in.)


Solution

  • According to laravel docs:

    Once the attribute has been added to the appends list, it will be included in both the model's array and JSON forms. Attributes in the appends array will also respect the visible and hidden settings configured on the model.

    The test attribute will not appear within $attributes until you call the toArray() or toJson() functions.

    The User instance attributes array are not an array representation of the User class.

    If you are working with a User object, then you can get the accessor attributes using $user->test.

    If you want the array or json representation of the User object, then return it as an array/json $user->toArray() or $user->toJson() - now accessors included in the $appends array will automatically be included.

    Hope it helps.