Search code examples
phplaravellaravel-5laravel-5.5laravel-validation

Is there a way to use parameters in custom \Illuminate\Contracts\Validation\Rule


One way to write custom validation rule in Laravel is by calling Artisan method make:rule:

php artisan make:rule EmptyIf

Then I don't know how to handle parameters. "Parameters" means something like require_if:foo,bar. The \Illuminate\Contracts\Validation\Rule interface has only two arguments for passes function:

public function passes($attribute, $value);

So I can't understand where I should add parameters. I know I can extends the validator via a Service provider, just like this:

Validator::extend('foo', function ($attribute, $value, $parameters, $validator) { 
    //
});

But it seems it's an old way, and in my point of view a bit more messy. Is there a way to handle parameter in passes function of a Rule?


Solution

  • You can define constructor for your custom rule and then pass your paramets in custom rule object. Custom rule:

    class CustomRule implements Rule
    {
        private $params = [];
    
        public function __construct($params)
        {
            $this->params = $params;
        }    
    
        public function passes($attribute, $value)
        {
            return /*Here you can use $this->params*/;
        }
    }
    

    Validation:

    $request->validate([
        'input' => ['rule', new CustomRule(['param1','param2','paramN'])],
    ]);