skip to Main Content

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.

2

Answers


  1. 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.");
                }
           }
      });
    
    Login or Signup to reply.
  2. 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'],
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search