Laravel验证-如何检查给定数组中是否存在值


Laravel Validation - How to check if a value exists in a given array?

所以,好吧,我从验证文档中尝试了很多规则,但都给了我相同的错误,说

数组到字符串转换

以下是我添加数组的方法:

$this->validate($request,[
                'employee' => 'required|in:'.$employee->pluck('id')->toArray(),
            ],[
                'employee.in' => 'employee does not exists',
            ]);

关于如何实现这一点,有什么提示吗?

我创建了一个自定义验证器,但仍然传递数组似乎是不可能的

将数组隐含为字符串并用逗号连接。

'employee' => 'required|in:'.$employee->implode('id', ', '),

这将生成验证器在进行in比较时所期望的正确逗号分隔字符串。

编辑

这仍然有效,但不再是拉雅维利式的方式。请参阅@nielsiano的答案。

您现在可以使用Rule类,而不是像正确答案中描述的那样自己内爆值。简单操作:

$ids = $employee->pluck('id')->toArray();
['employee' => ['required', Rule::in($ids)]];

如在";在";规则

这可以通过以下方式实现

  1. 您可以这样做,您需要用户在脚本的顶部使用Illuminate''Validation''Rule

    $request->validate ([
         'someProperty' => [
             'required',
              Rule::in(['manager', 'delivery_boy', 'stuff'])
         ]
    ]);
    
  2. 您也可以在中这样做:required一个字符串,如'required|in:manager,delivery_boy,stuff'

    "必需| in:"。内爆(",",$rules)

    $rules = ['manager', 'delivery_boy', 'stuff'];
    $request->validate([
        'someProperty' => "required|in:" . implode(", ",$rules)
    ]);
    
  3. 当您使用Validator类时,这种方式将起作用

    'Validator::make($request->all(),[
            'someProperty' => [
                'required',
                Rule::in(['manager', 'delivery_boy', 'stuff'])
            ]
        ])
    
  4. 当您使用Laravel表单请求类进行验证请求时

    public function rules(): array
    {
        return [
            'someProperty' => [
                'required',
                Rule::in(['manager', 'delivery_boy', 'stuff'])
            ]
        ];
    }
    
    public function authorize(): bool
    {
        return true;
    }