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'
]);
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.
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']
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With