Jag*_*rma 1 php mysql api json laravel
在这里,我面临数据库中重复条目的问题。我在控制器中设置了唯一的患者 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);
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的要求,一切正常,但代码抛出以下异常:
QueryException SQLSTATE[23000]: 完整性约束违规:1062 关键 'patients_email_unique' 的重复条目 'front@gmail.com'
这是我对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();
});
Run Code Online (Sandbox Code Playgroud)
您可以使用 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',
]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6099 次 |
| 最近记录: |