laravel 模型访问器在 laravel 5.8 中不起作用

laravel model accessors not working in laravel 5.8

使用 User::find(1) 时,属性(在本例中为全名)不显示; (实际上 returns 一个用户实例)并且访问器内部的 dd("test") 也没有被调用

我已经使用 tinker 对模型进行了 dd,并且我已经尝试在 $request->user() 输出上使用 dd returns 相同。

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";
    }

}

我希望具有字段 full_name 的用户属性返回 "test"。 (或者如果你让 dd 进入,则转储并死亡。)

根据 laravel 文档:

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.

在您调用 toArray()toJson() 函数之前,test 属性不会出现在 $attributes 中。

User 实例属性数组不是用户 class 的数组表示。

如果您正在使用 User 对象,那么您可以使用 $user->test 获取访问器属性。

如果您想要 User 对象的数组或 json 表示,则 return 它作为 array/json $user->toArray()$user->toJson() - 现在 $appends 数组中包含的访问器将自动包含在内。

希望对您有所帮助。

只需将其放入您的模型中:

protected $appends = ['full_name'];

并且它会调用你的getFullName属性,默认添加。它是专门为 api 建筑引入的。