Laravel 模型属性高级用法

文件位置:

D:\phpStudy\WWW\xxx\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php

隐藏属性:

protected $hidden = ['password'];

显示属性:

protected $visible = ['first_name', 'last_name'];

临时暴露隐藏属性:

return $user->makeVisible('attribute')->toArray();

类似的,如果你想要隐藏给定模型实例上某些显示的属性,可以使用 makeHidden 方法:

return $user->makeHidden('attribute')->toArray();

注意一定要先定义像追加的字段名,这相当于临时给model加字段,所以后面就可以像操作正常字段那样操作。

protected $appends = ['is_admin'];
public function getIsAdminAttribute()
{
    return $this->attributes['admin'] == 'yes';
}

运行时追加:

你可以在单个模型上使用 append 方法来追加属性,或者,你可以使用 setAppends 方法为给定模型覆盖整个追加属性数组:

return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();
    protected $appends = ['telephone', 'email'];
    public function getTelephoneAttribute()
    {
        return $this->attributes['telephone'] = $this->customers->telephone;
    }

    public function getEmailAttribute()
    {
        return $this->attributes['email'] = $this->customers->email;
    }

猜你喜欢

转载自blog.csdn.net/zhezhebie/article/details/81105083
今日推荐