如何从控制器验证器传递自定义验证规则中的某些变量?
例如:
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
}
.....
我需要将变量$someVariableINeed
从RegisterController
传递到\App\Rules\CustomValidationRule
。
类似于max:255
的工作方式。我想将255
传递到我的自定义规则中。
答案 0 :(得分:2)
将其添加为自定义验证参数,如下所示:
class CustomValidationRule extends Rule
{
public $max;
public function __construct($max = 255)
{
$this->max = $max;
}
}
您可以使用$this->max
之类的passs方法访问它
并像这样初始化值:
new CustomValidationRule(255)