Laravel catch Eloquent “Unique” field error

前端 未结 2 1243
无人共我
无人共我 2020-12-08 20:15

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:

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 20:30

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

提交回复
热议问题