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

淺唱寂寞╮ 提交于 2019-12-06 01:27:17

问题


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 validator but still passing array seems to be not possible


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/36413073/laravel-validation-how-to-check-if-a-value-exists-in-a-given-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!