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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36413073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:31:59  来源:igfitidea点击:

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

phparraysvalidationlaravellaravel-5.2

提问by Meta Pakistani

So, okay i tried a lot of rules from validation docs but all give me same error saying

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

Array to string conversion

数组到字符串的转换

Here is how I add the array:

这是我添加数组的方法:

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

Any hint on how to achieve this?

关于如何实现这一目标的任何提示?

i created a custom validatorbut still passing array seems to be not possible

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

回答by Ohgodwhy

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 incomparison.

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

Edit

编辑

This still works, but is not the Laravelesqueway of doing it anymore. See the answer by @nielsiano.

这仍然有效,但不再是Laravelesque的做法。请参阅@nielsiano 的答案。

回答by nielsiano

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

更新:您现在可以使用 Rule 类,而不是按照正确答案中的描述自行内爆值。简单地做:

['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

如文档中的“验证数组”部分所述:https: //laravel.com/docs/5.6/validation#validating-arrays