【问题标题】:Laravel Best Practice for Unique Fields Based on VariableLaravel 基于变量的唯一字段最佳实践
【发布时间】:2019-04-16 16:59:23
【问题描述】:

我很难定义这个标题。本质上,我的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))

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

【问题讨论】:

  • 您为什么不使用三列的唯一复合键而不是手动连接和存储冗余字段?
  • 如果用户收到此错误,您希望他/她做什么?更改姓名或生日?插入垃圾数据? firstname + lastname +birthdate 的元组并不像你想象的那么独特。

标签: laravel


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多