laravel如何返回html中显示的sql错误?

drnojrws  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(396)

问题

我在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 not successful,duplicate entry”?

mcdcgff0

mcdcgff01#

你可以用 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()->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.']);
    }
    else{
     return back()->withErrors($e->getMessage());
    }
}

或者你可以先找到/检查数据,如果已经存在就发送错误。例子:

$contact = Contact::where('email',$request->email)->first();
if($contact)
{
   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.']);
}
7gyucuyw

7gyucuyw2#

您可以将错误捕获为:

try
{  
   // below sql query
   $contact = Contact::find($id);
   // ...
   $contact->save();
   return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
// if catch any sql error then below code will execute
} catch(\Illuminate\Database\QueryException $e) {
     // return $e->getMessage(); // error message
     return back()->withErrors(["post not successful, duplicate entry"]);
}

相关问题