Laravel 5模型:在Eloquent中不包含某些栏目


Laravel 5 Model: Do not include certain columns in Eloquent

我正试图找到一个更容易的方法来实现这个简单的函数。基本上,我正在做的是动态加载一个基于Eloquent模型的表单。我不想在模型中包含某些列,如id和created_at和update_at列。我可以用下面这段代码来完成:

得到控制器:

$cms_information = collect(CmsUserInformation::where('users_id', Auth::user()->id)->first()->toArray());
$cms_information->forget('id');
$cms_information->forget('users_id');
$cms_information->forget('created_at');
$cms_information->forget('updated_at');
$cms_information->all();
return view('cms::admin.profile', ['user' => Auth::user(), 'cms_information' => $cms_information]);

然后,我将循环遍历表单中的字段并像这样发布它们:

Post控制器:

$profile = CmsUserInformation::where('users_id', Auth::user()->id)->first();
$cms_user_information = Input::except('_token', 'email', 'password');
foreach($cms_user_information as $field => $info ) {
    $profile->$field = $info;
}
$profile->save();

My Eloquent table:

id
user_id
first_name
last_name
email
created_at
updated_at

这完全是我想要的,但我觉得这是一种使用Eloquent对象来完成这一任务的快速而肮脏的方式。是否有人有一种方法来完成同样的事情,但只使用Eloquent对象,而不是转换为数组并使用collect()函数?

您可以在Eloquent模型上使用$hidden属性:

class CmsUserInformation extends Model
{
    protected $hidden = [
        'id',
        'users_id',
        'created_at',
        'updated_at',
    ];
}

这将在模型最终序列化时自动排除给定的属性。


如果您只想将其隐藏在特定的实例中,请使用setHidden方法:

$info = CmsUserInformation::where('users_id', Auth::id())->first();
$info->setHidden([
    'id',
    'users_id',
    'created_at',
    'updated_at',
]);

在你正在使用的模型中使用隐藏属性,像这样:

class User extends Model{
    protected $hidden=[
               'id',
               'created_at',
               'updated_at'
    ];
...
}