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

886

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

404

Answer

Solution:

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 anin comparison.

Edit

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

364

Answer

Solution:

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

People are also looking for solutions to the problem: php - My android registration App is working on my emulator when i use the unique ip 10.0.2.2 but not on real device

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.