Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate an array of integers

Given an array of integers:

[1, 2, 3, 4, ...]

How can I use the validator to check if each of these exists in a table? Possible without a foreach loop?

$validator = Validator::make($request->all(), [
    'array' => 'required|exists:users,id'
]);
like image 436
user7675955 Avatar asked Mar 08 '17 03:03

user7675955


2 Answers

Your validation as written should work. If the exists validation is used with an array, it will automatically use where in for the exists query.

So, given your validation as you have written, the validation will get the count of the users records where the id field is in the list of ids provided by your array input.

Therefore, if your array is [1, 2, 3, 4], it will get the count where users.id in (1,2,3,4), and compare that to the count of the elements in your array array (which is 4). If the query count is >= the array count, validation passes.

Two things to be careful about here: if the column you're checking is not unique, or if your array data has duplicate elements.

If the column you're checking is not unique, it's possible your query count will be >= the array count, but not all ids from your array actually exist. If your array is [1, 2, 3, 4], but your table has four records with id 1, validation will pass even though records with ids 2, 3, and 4 don't exist.

For duplicate array values, if your array was [1, 1], but you only have one record with an id of 1, validation would fail because the query count will be 1, but your array count is 2.

To work around these two caveats, you can do individual array element validation. Your rules would look something like:

$request = [
    'ids' => [1, 2, 3, 4],
];

$rules = [
    'ids' => 'required|array',
    'ids.*' => 'exists:users,id', // check each item in the array
];

$validator = Validator::make($request, $rules);

dd($validator->passes(), $validator->messages()->toArray());

Keep in mind that each element will be validated individually, so it will run a new query for each element in the ids array.

like image 109
patricus Avatar answered Oct 06 '22 21:10

patricus


You can make your custom rule:

public function validateArrayInt($attribute, $value, $parameters){  
    return array_filter(value, 'is_int')
}

Then:

$validator = Validator::make($request->all(), [
    'array' => ['required', 'array_int', 'exists:users,id']
]);
like image 38
manix Avatar answered Oct 06 '22 22:10

manix