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

30,974

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

Edit

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

Solution 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

Share:
30,974
Metabolic
Author by

Metabolic

Sipping Plutonium

Updated on July 09, 2022

Comments

  • Metabolic
    Metabolic almost 2 years

    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

  • kamasuPaul
    kamasuPaul about 3 years
    This is a much cleaner approach. Here the link to its documentation in laravel 8.