Home » Php » How to access other input attributes in Validator::extend?

How to access other input attributes in Validator::extend?

Posted by: admin October 29, 2017 Leave a comment

Questions:

As the question title states:
How can you access other input attributes when using Validator::extend?

Upon inspecting Laravel’s built-in Validator class, I can see it uses $this->data to access other attributes; however you can’t directly use $thisin the closure that Validator::extend requires.

It seems like manually extending the Validator class (through a custom class) is the only option… Am I correct? If so, this seems to me like a serious limitation for converting validators into packages as each package would extend the base Validator class for which PHP would eventually just retains the last defined extension (and thus rendering other validator packages unusable…). Or am I missing something?

Thanks.

EDIT

I also tried to wrap it up in a package following this method by Jason Lewis but I keep getting a BadMethodCallException stating that the validation method could not be found… The package is psr-0 compliant and I’m pretty sure it’s not a namespacing issue.

Answers:

After a bit of testing, you can access the array if you use a class and not a callback. As it extends the Validator class.

class TestRulesValidator extends \Illuminate\Validation\Validator
{

    public function validateTestRule($attribute, $value, $parameters)
    {
        var_dump($this->data);

        exit();
    }

}

From the validation documentation, use:

Validator::resolver(function($translator, $data, $rules, $messages) {
    return new TestRulesValidator($translator, $data, $rules, $messages);
});

Your rule name would be test_rule. Remove the validate keyword and convert to underscore case.

Just tested this on fresh installation and it works.

Edit – You can also use the normal extend method and pass an extra parameter.

class TestRulesValidator
{

    public function validateTestRule($attribute, $value, $params, $validator) {
        var_dump($validator->getData());
    }

}

Validator::extend('test_rule', '[email protected]');