首页 > 解决方案 > 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 错误。

在这种情况下,如何显示自定义消息,例如“发布不成功,重复条目”?

标签: phpmysqllaravellaravel-8

解决方案


您可以通过使用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>

推荐阅读