Search code examples
phparrayslaravellaravel-validation

Check if values in array are in another array using Laravel Validation


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?


Solution

  • 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