【问题标题】:Laravel How do I return back with SQL errors displayed in HTML?Laravel 如何返回以 HTML 显示的 SQL 错误?
【发布时间】:2021-04-06 21:28:38
【问题描述】:

问题

我在我的 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 错误。

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

【问题讨论】:

    标签: php mysql laravel laravel-8


    【解决方案1】:

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

    【讨论】:

    • 代码显示“我们收到了您的消息。我们会尽快回复您。”但它没有显示“您的消息可能重复。您刷新页面了吗?”你能告诉我如何显示第二条消息吗?
    • 我更新了答案,最好对你的情况使用这样的错误处理。
    • 我找到了自己的解决方案。我将此代码添加到我希望它显示错误的位置。 @if($errors->any())

      {{$errors->first()}}

      @endif
    • 你能支持我的问题吗?这个系统会阻止我提出更多问题,除非它被支持。
    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 2019-07-07
    • 2019-08-11
    • 2021-05-08
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多