英文:
Laravel validation with a nested where conditions
问题
public function rules()
{
return [
'name' => 'required',
'roles.*' => [Rule::exists(Role::class, 'id')
->where(function (Builder $q) {
$q->where('name', '访客')
->where('status', '!=', 0);
})
];
}
英文:
Goal: Validation of a user update input with the goal to not allow a special case. A relation (role) of the user model should be checked. A user may not be assigned the role: Visitor
with the status 0
. Everything else is allowed.
Problem: With my implementation of the Where conditions the validation will fail already at the first condition. So if the role is visitor, the validation fails. The second condition with the status is not considered at all.
users: id, name
roles: id, name, permissions, status
My validation rules method:
public function rules()
{
return [
'name' => 'required',
'roles.*' => [Rule::exists(Role::class, 'id')
->where(function (Builder $q) {
$q->where('name', 'Visitor')
->where('status', '!=', 0);
})
];
}
答案1
得分: 2
如果你想限制 roles.*
,我假设这些是来自你的 Role
模型表 roles
的 id
,你可以使用 Rule::notIn()
方法:
public function rules() {
return [
'name' => 'required',
'roles.*' => [
Rule::notIn(Role::where('name', 'Visitor')->where('status', 0)->pluck('id'))
]
];
}
这将翻译成 Rule::notIn([1])
(将 1
替换为 Visitor
角色的 id
),如果 roles.*
中的任何值是 1
,则验证将失败。
附注:你也可以使用 Rule::in()
来实现,但查询略微复杂一些。
参考链接:
https://laravel.com/docs/10.x/validation#rule-not-in
https://laravel.com/docs/10.x/validation#rule-in
英文:
If you want to limit roles.*
, which I assume are id
s from your Role
Model's Table roles
, you can use the Rule::notIn()
method:
public function rules() {
return [
'name' => 'required',
'roles.*' => [
Rule::notIn(Role::where('name', 'Visitor')->where('status', 0)->pluck('id'))
]
];
}
This will translate to Rule::notIn([1])
(replacing 1
with whatever the id
of the Visitor
Role is), and if any value of roles.*
is 1
, your validation will fail.
Sidenote: You can do this with the Rule::in()
too, but the query is slightly more complicated
References:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论