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

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

问题描述:

我尝试了很多验证文档中的方法,但都给出了同样的错误说明:

Array to string conversion

下面是我如何添加数组的:

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

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

我创建了一个自定义验证器,但仍然无法传递数组。

Implode the array as a string and join it on commas.

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

This will make the correct comma separated string that the validator expects when making an in comparison.

Update: You are now able to use the Rule class instead of imploding values yourself as described in the correct answer. Simply do:

['someProperty' => ['required', Rule::in(['needed', 'stuff'])]];

As mentioned in the 'validating arrays' section in the documentation: https://laravel.com/docs/5.6/validation#validating-arrays