Laravel catch Eloquent “Unique” field error

前端 未结 2 1242
无人共我
无人共我 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条回答
  •  臣服心动
    2020-12-08 20:39

    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
        }
    }
    

提交回复
热议问题