在这里,我面临数据库中重复条目的问题。我在我的控制器中设置了一个唯一的患者 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();
});