How to pass parameters in Laravel Rule?

Here is a simpler and updated way of accomplishing this, without extending the validator. You can access the passed param in the Rule's constructor, so just set a globally scoped variable and now you can reference it inside of the passes() method. You could even use the same approach to have the value in the validator message.

The validate call:

case 'measurement':
 $request->validate([
   'updates.*.value' => [
   new Measurement('foo-bar'),
   ],
 ]);
 break;

The Rule:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Measurement implements Rule
{
/**
 * Create a new rule instance.
 *
 * @param $param
 */
public function __construct($param)
{
    $this->type = $param;
}

public $type;
/**
 * Determine if the validation rule passes.
 *
 * @param string $attribute
 * @param mixed $value
 * @param array $parameters
 * @return bool
 */
public function passes($attribute, $value)
{
    dd($this->type, 'params');
    return;
}

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);
 });

Tags:

Laravel