Validate an array of integers

馋奶兔 提交于 2019-12-05 11:29:37

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.

manix

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']
]);
Heartbeat

Try this to check whether your response array is json.

return response()->json($yourArr)->setEncodingOptions(JSON_NUMERIC_CHECK);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!