Victordb
Victordb

Reputation: 549

Pass data to laravel custom validation rule

How can I pass some variable in a custom validation rule from the controller validator?

For example:

      class RegisterController extends Controller {

             $someVariableINeed = 2

             protected function validator(array $data) {
                    return Validator::make($data, [
                                'name' => 'required|string|max:255',
                                'email' => 'required|string|email|max:255|unique:users',
                                'password' => 'required|string|min:6|confirmed',
                                'someField' => ['required', new \App\Rules\CustomValidationRule]
                    ]);
                }
 .....

        }

And the \App\Rules\CustomValidationRule :

.....

     public function passes($attribute, $value) {
       if ($value == 1 && $someVariableINeed == 2) {
        return true
       }
       return false
     }

.....

I need to pass variable $someVariableINeed from the RegisterController to the \App\Rules\CustomValidationRule.

Something similar to how max:255 works. I want to pass into my custom rule the 255.

Upvotes: 1

Views: 3755

Answers (1)

user10896277
user10896277

Reputation:

Add it as a custom validation parameter like this:

class CustomValidationRule extends Rule
{
    public $max;

    public function __construct($max = 255)
    {
        $this->max = $max;
    }
}

And you could access it in the passes method like $this->max

And initiate the value like this:

new CustomValidationRule(255)

Upvotes: 2

Related Questions