2

I want to check if all the values of my input, an array, are in another array. For example:

$my_arr = ['item1', 'item2', 'item3', 'item4'];

Validator::make($request, [
            'item' => [ /* what do i put here??? */ ],
        ]);

I don't think the rule in works, because that expects a single value as input, not an array. in_array doesn't work either. I've tried creating a custom rule or closure, but neither of those allow me to pass in a parameter (the array I want to check against). Especially since I want this same functionality for multiple arrays, for different inputs, it would be nice to have a generic rule that works for any array I give it.

If that's not possible, I suppose I need to create a rule for each specific array and use !array_diff($search_this, $all) as this answer says. Is there an alternative to this?

1 Answer 1

1

True that in doesn't accept an array but a string. So you can just convert the array into a string.

$my_arr = ['item1', 'item2', 'item3', 'item4'];

Validator::make($request, [
   'item' => [ 'in:' . implode(',', $my_arr) ],
]);

implode

Another better solution might be to use Illuminate\Validation\Rule's in method that accepts an array:

'item' => [ Rule::in($my_arr) ],

Laravel Validation - Rule::in

Sign up to request clarification or add additional context in comments.

1 Comment

Wait, so the validation rule works even if the input is an array? Just checking because that wasn't specified in the Laravel documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.