Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel catch Eloquent "Unique" field error

I am trying to identify when inserting a record using eloquent in Laravel when it throws an exception because of a unique field error.

The code I have so far is:

try {      $result = Emailreminder::create(array(                        'user_id' => Auth::user()->id,                        'email' => $newEmail,                        'token' => $token,               ));  } catch (Illuminate\Database\QueryException $e) {     return $e; } 

It throws an exception OK I just don't know what to do to identify it as a column duplicate error?

Thanks,

Gavin.

like image 282
Gavin Avatar asked Jan 10 '15 16:01

Gavin


2 Answers

I'm assuming you use MySQL, it's probably different for other systems

Okay first, the error code for duplicate entry is 1062. And here's how you retrieve the error code from the exception:

catch (Illuminate\Database\QueryException $e){     $errorCode = $e->errorInfo[1];     if($errorCode == 1062){         // houston, we have a duplicate entry problem     } } 
like image 50
lukasgeiter Avatar answered Sep 28 '22 08:09

lukasgeiter


add this code inside class Handler (exception)

if($e instanceof QueryException){         $errorCode = $e->errorInfo[1];                   switch ($errorCode) {             case 1062://code dublicate entry                  return response([                     'errors'=>'Duplicate Entry'                 ],Response::HTTP_NOT_FOUND);                     break;             case 1364:// you can handel any auther error                 return response([                     'errors'=>$e->getMessage()                 ],Response::HTTP_NOT_FOUND);                                         break;               }      }     ...     return parent::render($request, $exception); 
like image 37
Amirouche Zeggagh Avatar answered Sep 28 '22 08:09

Amirouche Zeggagh