Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

php - 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?

question from:https://stackoverflow.com/questions/65930937/check-if-values-in-array-are-in-another-array-using-laravel-validation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 IlluminateValidationRule's in method that accepts an array:

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

Laravel Validation - Rule::in


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...