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?

the_sky_is_pink
  • 109
  • 2
  • 11

1 Answers1

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

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
  • Wait, so the validation rule works even if the input is an array? Just checking because that wasn't specified in the Laravel documentation. – the_sky_is_pink Jan 28 '21 at 07:13