我怎样才能使用更新并一次创建验证器?现在,用户必须拥有唯一的电子邮件地址。但是当我更新它时会抛出一个已经存在的错误。
我该怎么办?
$validator = Validator::make($request->all(), [
'RoleId' => 'required|numeric',
'DepartmentId' => 'required|numeric|max:10',
'FirstName' => 'required|string|max:50',
'LastName' => 'required|string|max:50',
'email' => 'required|email|unique:employee|max:50',
'Gender' => 'required|numeric|max:1',
'password' => 'required|max:50',
'Address' => 'required|string|max:50',
'Zip' => 'required|string|max:50',
'City' => 'required|string|max:50',
'BirthDate' => 'required:date|max:10',
'StartDate' => 'required:date|max:10',
'EndDate' => 'required:date|max:10',
'Suspended' => 'required:numeric:max:1'
]);
答案 0 :(得分:0)
首先我假设您在Laravel 5上。如果没有,那么这可能不适用。但是您可以指定要忽略唯一验证中的行:
'email' => 'required|email|max:50|unique:employee,email,' . $input->id,
因此,您可以先检查并调整验证器字符串,也可以使用sometimes
选项。您只需要创建隐藏字段或者传递$model->id
的值。
<input type='hidden' value='{{$model->id}}' name='id' />
选项1
$email_validator = "unique:employee,email";
if($request->input('id',0) > 0) {
$email_validator .= "," . $request->input('id');
}
$validator = Validator::make($request->all(), [
...
'email' => 'required|email|max:50|' . $email_validator,
...
]);
选项2
$validator = Validator::make($request->all(), [
...
'email' => 'required|email|max:50',
...
]);
$validator->sometimes('email','unique:employee,email,' . $request->input('id'),function($input){
return $input->id > 0;
});
$validator->sometimes('email','unique:employee',function($input){
return $input->id == 0;
});