Laravel 验证与嵌套的条件查询

huangapple go评论57阅读模式
英文:

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 模型表 rolesid,你可以使用 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 ids 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:

https://laravel.com/docs/10.x/validation#rule-not-in

https://laravel.com/docs/10.x/validation#rule-in

huangapple
  • 本文由 发表于 2023年6月22日 01:33:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定