从自定义验证对象中检索参数

时间:2018-07-27 14:02:01

标签: laravel validation laravel-5.5

我有基本的自定义validation rule。在

public function passes($attribute, $value)
{
    foreach ($parameters as $key)
    {
        if ( ! empty(Input::get($key)) )
        {
            return false;
        }
    }

    return true;
}

我已经定义了规则。我虽然需要从parameters中检索rule,但是passes方法并未将其作为argument提供。

如果我使用提供Validator:extends...的样式4 arguments: $attribute, $value, $parameters, $validator。然后,我可以轻松地使用parameters,很遗憾,我不得不使用这种方式。

编辑:

清除问题。我想检索parameters of the rule,就像用其他编码方式一样: 'not_empty:user_id'。冒号后面的值数组。

2 个答案:

答案 0 :(得分:1)

我相信唯一的方法是使用规则对象时从请求中检索它。

例如:

public function passes($attribute, $value)
{
    foreach ($parameters as $key) {
        // Or using \Request::input($key) if you want to use the facade
        if (!empty(request()->input($key)) { 
            return false;
        }
    }

    return true;
 }

答案 1 :(得分:1)

编辑:---

自定义规则对象只是一个对象。如果您想传递更多的参数,可以在其构造函数中使用:

$request->validate([
    'name' => ['required', new MyCustomRule('param', true, $foo)],
]);

然后保存这些内容并在passes函数中使用它们。

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

然后在您的passs函数中使用:

$this->myCustomParam
相关问题