2
votes

I am trying to make a custom validator using extension which will be part of an object in an array. The validation rules would be as:

$this->validate($request, [
    '*.odds' => 'required',
    '*.outcome_id' => 'required|oddIs:*.odds'
]);

So, the rule would take the value of outcome id and compare it's odds property with the odds in input.

Validator::extend('oddIs', function($attribute, $value, $parameters, $validator) {
    $outcome = Outcome::find($value);

    return $outcome->odds == array_get($validator->getData(), $parameters[0]);
});

As you can see I am trying to make it work with the astrike. But I could not find a way to parse the attribute name and generate a key with the relative index.

Now in short, the solution I am looking for is to validate comparing two fields where the fields will be nested in array.

FYI: The validation data will be coming as JSON.

Similar issue that worked on possibly an older version of laravel: https://laravel.io/forum/11-09-2014-create-custom-validation-rule-which-takes-two-fields-as-arguments

1

1 Answers

0
votes

After going through the source code, it is possible to accomplish this with extendDependent() method. It isn't documented in the main documentation. Changing the validation extension code to the following will change all parameters to the relative key.

Validator::extendDependent('oddIs', function($attribute, $value, $parameters, $validator) {
    $outcome = Outcome::find($value);

    return $outcome->odds == array_get($validator->getData(), $parameters[0]);
});