Search code examples
laravel

How to pass parameters in Laravel Rule?


I would like to move this code to the App\Rule:

//Currently in class AppServiceProvider extends ServiceProvider

Validator::extend('empty_if', function ($attribute, $value, $parameters, $validator) {
   return ($value != '' && request($parameters[0]) != '') ? false : true;
});

So that it should be this:

//in: App\Rules\EmptyIf

public function passes($attribute, $value, $parameters)
{
   return ($value != '' && request($parameters[0]) != '') ? false : true;
}

But my problem is, that I cannot pass $parameters with

Validator::extend('empty_if', 'App\Rules\EmptyIf@passes');

How would you pass parameters to Laravel Rule?


Solution

  • If I understand what you need correctly you don't need to extend the validator.

    You seem to have class:

    class EmptyIf extends Rule {
          public function passes($attribute, $value, $parameters) { }
    }
    

    Then you can just use this as:

    $this->validate($data, [ "entry" => [ new EmptyIf() ] ]);
    

    You might be able to do both using:

    Validator::extend('empty_if', function ($attribute, $value, $parameters) {
        return (new EmptyIf())->passes($atribute, $value, $parameters);
     });