这里我面临着数据库中重复条目的问题。我在控制器中设置了一个唯一的患者ID,我希望添加具有相同电子邮件但具有唯一电话号码的用户。
我在控制器功能中所做的和尝试:
public function store(Request $request) {
$validator = \Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'phone'=>'required|min:11|numeric|unique:patients',
'birth_date' => 'required',
'gender' => 'required',
'address' => 'required',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return $errors->toJson();
} else {
$fileNameToStore = 'defaultimg/avatar.png';
$post = new patient;
$post->name = $request->input('name');
$post->email = $request->input('email');
$post->picture = $fileNameToStore;
$post->birth_date = $request->input('birth_date');
$post->gender = $request->input('gender');
$address = htmlspecialchars($request->input('address'));
$post->address = $address;
$post->patient_id = 'PID' . rand(999, 9999999999999);
$post->phone = $request->input('phone');
$post->save();
return response(array(
'error' => false,
'message' => 'Patient added successfully', 'patientid' => $post->patient_id,), 200);
}
}
根据我的要求,一切正常,但代码会引发以下异常:
QueryException SQLSTATE [23000]:完整性约束违规:1062重复条目'front_gmail.com',用于键'patients_email_unique'
以下是我对patients
表的迁移:
Schema::create('patients', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('birth_date');
$table->string('gender');
$table->string('address');
$table->string('patient_id');
$table->string('picture');
$table->string('phone')->unique();
$table->rememberToken();
$table->timestamps();
});
答案 0 :(得分:2)
$this->validate($request,[
'email' => 'required|email|unique',
]);
在您的迁移中
$table->string('email')->unique();
答案 1 :(得分:1)
您应该将unique
验证规则添加到email
字段,如下所示:
$validator = \Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique',
'phone'=>'required|min:11|numeric|unique:patients',
'birth_date' => 'required',
'gender' => 'required',
'address' => 'required',
]);
答案 2 :(得分:1)
更改此行
$table->string('email')->unique();
要
$table->string('email');
答案 3 :(得分:1)
您可以使用laravel验证来检查特定表中的唯一值。
$validator = \Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:patients,email',
'phone'=>'required|min:11|numeric|unique:patients',
'birth_date' => 'required',
'gender' => 'required',
'address' => 'required',
]);