我从这里看到: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'
],
如果用户是访客(无登录),则作者需要
是否可以做到?
答案 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);
}
}
但同样,您需要覆盖标准行为,由您自行决定哪种解决方案最符合您的需求。