laravel - 我如何用更好的方式隐藏 Laravel 模型字段

标签 laravel eloquent

在我的例子中,我隐藏了我的 Eloquent 领域,如下所示:

public function __construct(array $attributes = array())
{
    parent::__construct($attributes);
    $user = auth()->user();
    $hiddenFields = [];
    if(!$user || $user && $user->id !== $this->user_id) {
        $hiddenFields = [
            'phone', 'employees', 'email',
            'created_at', 'updated_at', 'id', 'description'
        ];
    }
    $this->hidden = array_merge($this->hidden, $hiddenFields);
}

可以更好地隐藏字段吗?

最佳答案

您可以直接在模型中使用 $visible$hidden ,因此在执行对 ->toArray() 的调用时,它们将不会'无法显示。

文档: https://laravel.com/docs/master/eloquent-serialization#hiding-attributes-from-json

关于laravel - 我如何用更好的方式隐藏 Laravel 模型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722284/

相关文章:

file - Laravel 文件与存储外观

javascript - 如何使用 Laravel rest api 在 vue-tables-2 上添加分页?

mysql - 使用 Laravel 4 嵌套集合类别

php - 从两个相关表/模型中选择特定列

php - Laravel 从所有 View 访问数据

php - 排队的 Laravel 通知卡在 AWS SQS 上

php - 在 laravel 中使用 makeHidden 的正确方法

php - Eloquent 查找错误的列

Laravel-如何在 parent 改变时更新所有 child ?

arrays - Laravel - 从数据库 View 中显示数组/字符串对象