Laravel custom validation with rule object: Access other fields or validator

Viewed 504

I am using the rule object from Laravel 8

artisan make:rule RequireBetweenOf

See https://laravel.com/docs/8.x/validation#using-rule-objects

How do I access other fields or the validator?

I need to check other data in the validator.

I know how it works for for Validator::extend() as 4. parameter but that does not work for Illuminate\Contracts\Validation\Rule. I have also seen that there is a answer using request(). But that is a hack, because validator data and request might not be the same. There might be no request at all.

1 Answers

TL;DR

use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Contracts\Validation\DataAwareRule;

class RequireBetweenOf implements Rule, DataAwareRule, ValidatorAwareRule

I found the password rule is using the validator: \Illuminate\Validation\Rules\Password::setValidator. Digging deeper this is used here: \Illuminate\Validation\Validator::validateUsingCustomRule.

Key are those two interfaces: \Illuminate\Contracts\Validation\ValidatorAwareRule and \Illuminate\Contracts\Validation\DataAwareRule

Related