如何在验证器接口laravel中添加条件?

时间:2017-09-05 14:22:35

标签: laravel laravel-5.4 required laravel-validation

我从这里看到:https://github.com/andersao/laravel-validator

例如代码如下:

use \Prettus\Validator\LaravelValidator;

class PostValidator extends LaravelValidator {

    protected $rules = [
        ValidatorInterface::RULE_CREATE => [
            'title' => 'required',
            'text'  => 'min:3',
            'author'=> 'required'
        ],
        ValidatorInterface::RULE_UPDATE => [
            'title' => 'required'
        ]
   ];

}

我想添加条件,如果用户是成员(if(Auth::id())),那么字段作者不需要

所以验证器是这样的:

ValidatorInterface::RULE_CREATE => [
        'title' => 'required',
        'text'  => 'min:3'
],

如果用户是访客(无登录),则作者需要

是否可以做到?

2 个答案:

答案 0 :(得分:0)

Laravel documentation有一个关于自定义验证器的部分

答案 1 :(得分:0)

由于您无法在类属性中执行指令,因此可以尝试覆盖create实例的Repository方法,以便在创建实际需要之前修改$rules参数的地方。

因此,在Repository课程中,覆盖方法create

public function create(array $attributes)
{

    $oldRule = $this->rules[ValidatorInterface::RULE_CREATE]['author'];

    if(Auth::guest()){ // or use the preferred check
        unset($this->rules[ValidatorInterface::RULE_CREATE]['author']);
    }

    $this->makeValidator();
    $res = parent::create($attributes);

    $this->rules[ValidatorInterface::RULE_CREATE]['author'] = $oldRule;

    return $res;
}

修改

另一种方法可能是在PostValidator中指定自定义验证逻辑,如下所示:

use \Prettus\Validator\LaravelValidator;

class PostValidator extends LaravelValidator {

    const RULE_CREATE_FOR_MEMBER = 'RULE_CREATE_FOR_MEMBER';

    protected $rules = [
        ValidatorInterface::RULE_CREATE => [
            'title' => 'required',
            'text'  => 'min:3',
            'author'=> 'required'
        ],
        self::RULE_CREATE_FOR_MEMBER => [
            'title' => 'required',
            'text'  => 'min:3'
        ],
        ValidatorInterface::RULE_UPDATE => [
            'title' => 'required'
        ]
   ];

   public function passes($action = null)
   {
       if($action == ValidatorInterface::RULE_CREATE && \Auth::id()) {
          $action = self::RULE_CREATE_FOR_MEMBER;
       }

       return parent::passes($action);
   }

}

但同样,您需要覆盖标准行为,由您自行决定哪种解决方案最符合您的需求。