简体   繁体   中英

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

The problem

I created a constraint in my SQL database to prevent duplicate entries. The initial laravel form submission works fine. I get back the correct message. When I try to throw a duplicate entry, the app, as expected, throws an error.

This is my Controller. A successful form submission does throw the correct error:

$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.']);

Question

How do I display that error on the HTML screen? Instead of having the page display the following?

抛出错误

Basically the contact form submits information into the database using laravel. When successful, it displays a success message by redirecting it. When not successful, (because of a SQL Unique constraint blocking duplicate entries) so far I've managed to make it throw a SQL error.

How do I display a custom message, like "post not successful, duplicate entry" in that case?

You can do it by using try catch and query exception:

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());
    }
}

or another way you can find/check the data first, if already exist just send the error. example:

$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.');
}

dont forget to get the error on the form view using like below:

<script>
  @if(session()->has('error'))
    alert('{{session()->get('error')}}')
  @endif
 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM