仅当用户为访客时,我才想验证姓名和电子邮件(必填)。我该怎么做呢?
我尝试粘贴if
条件。但是我认为这是不正确的:
if (Auth::check()) {
$request->validate([
'name' => 'required|string',
'email' => 'required|string',
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3'
]);
} else {
$request->validate([
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3'
]);
}
答案 0 :(得分:3)
我想不出可以执行此操作的验证规则,但是至少可以跳过else
条件来使代码更简洁一些,例如:
$rules = [
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3',
];
if (Auth::guest()) {
$rules['name'] = 'required|string';
$rules['email'] = 'required|string';
}
$request->validate($rules);
另一种选择是仅检查阵列中的需求,而只跳过授权用户验证中的字段。它更短,但还不那么干净:
$request->validate([
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3',
'name' => Auth::guest() ? 'required|string' : '',
'email' => Auth::guest() ? 'required|string' : '',
]);
顺便说一句,我建议将电子邮件地址验证为电子邮件地址:https://laravel.com/docs/5.7/validation#rule-email