将数据传递给laravel自定义验证规则

时间:2019-02-27 17:41:29

标签: laravel validation laravel-5.7

如何从控制器验证器传递自定义验证规则中的某些变量?

例如:

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

        }

还有\App\Rules\CustomValidationRule

.....

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

.....

我需要将变量$someVariableINeedRegisterController传递到\App\Rules\CustomValidationRule

类似于max:255的工作方式。我想将255传递到我的自定义规则中。

1 个答案:

答案 0 :(得分:2)

将其添加为自定义验证参数,如下所示:

class CustomValidationRule extends Rule
{
    public $max;

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

您可以使用$this->max之类的passs方法访问它

并像这样初始化值:

new CustomValidationRule(255)