Yup, the reason it is getting overridden is the Validator\Factory
class only stores one resolver
. The code for the function is here:
public function resolver(Closure $resolver) {
$this->resolver = $resolver;
}
I would assume that the point of the resolver
method is to extend the base validation class with your own. This makes sense as you could instantiate a UserRegistrationValidator
adding your own validation rules that have all the flexibility as the existing ones.
One issue with this is that it can be overridden with ease, this indicates to me that you should only call the resolver
method just before calling make
. Although more effort, it would stop rules from different packages potentially overriding other rules and even the base ones automatically.
But this does not work well for a package that only provides extra helpful rules. The simpler version to add a rule is:
Validator::extend('foo', 'FooValidator@validate');
This does not allow access to the input data, which is important for complex rules. The documentation example shows us this also:
class CustomValidator extends Illuminate\Validation\Validator
{
public function validateFoo($attribute, $value, $parameters) {
return $value == 'foo';
}
}
But wait! What the documentation doesn't tell you is that you can add on another parameter to get the instance of Validator
. Which I just found out myself whilst writing this answer and getting deep into the classes!
class TestRulesValidator
{
public function validateTestRule($attribute, $value, $params, $validator) {
var_dump($validator->getData());
}
}
Validator::extend('test_rule', 'TestRulesValidator@validateTestRule');
So to conclude, pass an extra parameter which will be the instance of the validator being used. I suspect this will also work with a callback too.
Hope this helps, it did for me!