Hey
Hey

Reputation: 195

Laravel validation distinct only for its siblings array element

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.

Upvotes: 1

Views: 101

Answers (2)

Joseph
Joseph

Reputation: 6269

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

Upvotes: 5

Al Amin
Al Amin

Reputation: 150

You can use 'after' to check for duplicates in each inner array, Like

$validator->after(function ($validator) use ($data) {
        foreach ($data as $index => $innerArray) {
            if (count($innerArray) !== count(array_unique($innerArray))) {
                $validator->errors()->add("bla.$index", "The elements in bla.$index must be distinct.");
            }
       }
  });

Upvotes: 0

Related Questions