Laravel 如何 return 返回并在 HTML 中显示 SQL 错误?

Laravel How do I return back with SQL errors displayed in HTML?

问题

我在 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 唯一约束阻止重复条目)到目前为止,我已经设法让它抛出 SQL 错误。

如何显示自定义消息,例如“post 不成功,重复输入”?

您可以使用 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());
    }
}

或者您可以先 find/check 数据的另一种方式,如果已经存在则发送错误。示例:

$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>