We have this validation code:
$data = [
[1, 2, 3],
[3, 4, 5]
];
$validator = \Validator::make([
"bla" => $data,
], [
'bla' => 'required|array',
'bla.*' => 'required|array|max:5|min:1',
'bla.*.*' => 'required|integer|distinct',
]);
if ($validator->fails()) {...}
As you can see, we added distinct
on the inner array. Currently, this code is getting an error:
The bla.0.2 field has a duplicate value.
The bla.1.0 field has a duplicate value.
What we are trying to achieve is only check if there is a duplicate on inner array. In this example, since all the inner arrays are unique, it should pass the validation.
distinct
seems to check everything. including other inner arrays.
Example:
This should pass:
$data = [
[1, 2, 3],
[3, 4, 5]
];
This should not pass since there are 2 4s on the first inner array.
$data = [
[4, 4, 3],
[3, 8, 5]
];
Any help would be appreaciated.
For some reason distinct
checks all of the sub-arrays
so to fix that you could fix it by write custom validation rule like this one
$data = [
[1, 2, 3],
[3, 4, 5]
];
$validator = Validator::make([
"bla" => $data,
], [
'bla' => 'required|array',
'bla.*' => [
'required',
'array',
'max:5',
'min:1',
function ($attribute, $value, $fail) {
if (count($value) !== count(array_unique($value))) {
$fail($attribute . ' contains duplicate values.');
}
}
],
'bla.*.*' => ['required', 'integer'],
]);