Laravel catches a "unique" field error

I am trying to determine when inserting a record using eloquence in Laravel when it throws an exception due to 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 duplicate column error.

Thanks,

Gavin.

+15
source share
2 answers

I assume you are using MySQL, it is probably different for other systems

Ok, first the error code for the repeated entry is 1062 . And here is how you extract 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 } } 
+37
source

add this code inside Handler class (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); 
0
source

Source: https://habr.com/ru/post/980805/


All Articles