php - Laravel 如何返回以 HTML 显示的 SQL 错误?
问题描述
问题
我在我的 SQL 数据库中创建了一个约束来防止重复条目。最初的 laravel 表单提交工作正常。我得到了正确的信息。当我尝试抛出重复条目时,应用程序如预期的那样抛出错误。
这是我的控制器。成功的表单提交确实会引发正确的错误:
$contact->save();
return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
return back()->withErrors(['Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.']);
问题
如何在 HTML 屏幕上显示该错误?而不是让页面显示以下内容?
基本上,联系表单使用 laravel 将信息提交到数据库中。成功后,它会通过重定向显示成功消息。如果不成功,(因为 SQL Unique 约束阻止重复条目)到目前为止,我已经设法让它抛出一个 SQL 错误。
在这种情况下,如何显示自定义消息,例如“发布不成功,重复条目”?
解决方案
您可以通过使用try catch
和查询异常来做到这一点:
try {
$contact->save();
return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
} catch(\Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == '1062'){
return back()->with('error', 'Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.');
}
else{
return back()->with('error', $e->getMessage());
}
}
或者您可以先找到/检查数据的另一种方式,如果已经存在,只需发送错误。例子:
$contact = Contact::where('email',$request->email)->first();
if($contact)
{
return back()->with('error', 'Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.');
}
不要忘记在表单视图上使用如下所示的错误:
<script>
@if(session()->has('error'))
alert('{{session()->get('error')}}')
@endif
</script>
推荐阅读
- php - PHP类型杂耍澄清
- python - 如何使用浮点类型的数据(边界框)训练神经网络
- css - 如何更改 React 图标的线宽?
- android - 确认 tx 时 UPI 付款 href 链接导致错误
- javascript - Javascript无法访问对象属性
- javascript - 如果一个按钮被点击了 x 次,我需要在我的网站上发生一个事件
- javascript - AddEventListener 对新添加的 innerHtml 不起作用?
- c++ - 如何在 cout 语句中将数字转换为小数?
- android - 如何在 Android 片段中制作 SnackBar?
- python-3.x - RIDE 工具无法在 Ubuntu 20.4 上安装