gpt4 book ai didi

php - Laravel:仅在某些路径中隐藏模型的属性

转载 作者:行者123 更新时间:2023-12-03 15:30:15 28 4
gpt4 key购买 nike

如何仅在某些 route 从模型隐藏某些属性,例如:

我正在使用 protected $ hidden来隐藏元素,但这会隐藏在我所有的函数或 Restful route (索引,显示)

 $hidden = [
'coachVisibility', 'thumbnail', 'studentVisibility',
'isHTML', 'studentIndex', 'coachIndex',
'isURL', 'source', 'path',
'status', 'updateTime', 'isfolder',
'parentResource', 'idModifierUser', 'idResourceType',
'idCreatorUser', 'idCreationCountry', 'user',
'country', 'resource'
];

我只想隐藏在Index函数中,而在show函数中,我不想隐藏任何东西。

最佳答案

您可以在模型上使用addHidden方法:

class UsersController
{
public function index ()
{
return User::all()->each(function ($user) {
$user->addHidden([.........]);
});
}
}

一旦 this PR被合并,您就可以直接在集合上调用它:

class UsersController
{
public function index ()
{
return User::all()->makeHidden([.........]);
}
}

根据您的评论,您可以将所有这些字段保留在模型的 $hidden属性中,而仅使它们在 show方法中可见:
public function show($id)
{
return CTL_Resource::where('idResource', $id)
->with('tags', 'quickTags', 'relatedTo')
->firstOrFail()->makeVisible([
'coachVisibility', 'thumbnail', 'studentVisibility'
]);
}

关于php - Laravel:仅在某些路径中隐藏模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36612164/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com