Laravel基于变量的唯一字段最佳实践

时间:2018-11-13 19:23:16

标签: laravel

我很难定义这个标题。本质上,我的patients表需要一个唯一的标识符列,我们通过将患者的名字和姓氏以及出生日期串联起来来实现。我想做的是找到一种在尝试插入数据库之前针对数据库进行检查并显示错误消息的方法。这是我目前拥有的:

$this->validate($request, [
    'doctor' => 'required|integer',
    'last_name' => 'required|string|max:255',
    'first_name' => 'required|string|max:255',
    'dob' => 'required|date_format:"m/d/Y"|max:255',
]);

$dobFix = date('Y-m-d', strtotime($request->dob));
$unique_id = $request->first_name . $request->last_name . $dobFix;

$patient = new Patient();
$patient->last_name = $request->last_name;
$patient->first_name = $request->first_name;
$patient->dob = $dobFix;
$patient->unique_id = $unique_id;
$patient->save();

$message = 'Patient ' . $request->first_name . ' ' . $request->last_name . ' was successfully added.';

return redirect()
    ->route('patients.index')
    ->with('success', $message);

当我尝试与此提交一个重复的条目时,我收到以下laravel错误页面:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 
'DuaneBartelli1986-06-22' for key 'patients_unique_id_unique' (SQL: 
insert into `patients` (`last_name`, `first_name`, `dob`, `unique_id`, 
`updated_at`, `created_at`) values (Bartelli, Duane, 1986-06-22, 
DuaneBartelli1986-06-22, 2018-11-13 13:16:37, 2018-11-13 13:16:37))

所以,这告诉我我需要知道的内容,但对用户没有任何帮助。我如何才能完成将其更改为错误消息(如成功消息)的显示,或者使其与其余请求信息一起验证?

1 个答案:

答案 0 :(得分:0)

  

如何将其更改为错误消息,例如显示的成功消息,或者使其与其余请求信息一起验证?

$patient->save();包装在一个try-catch中,使用户返回到出现更好错误消息的页面。

try {
    $patient->save();
} catch (\Exception $e) {
    return redirect('/yourUrl')->with('error', 'Your error message');
}