php Laravel 捕获 Eloquent “Unique”字段错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27878719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel catch Eloquent "Unique" field error
提问by Gavin
I am trying to identify when inserting a record using eloquent in Laravel when it throws an exception because of a unique field error.
我试图确定何时在 Laravel 中使用 eloquent 插入记录时由于唯一字段错误而引发异常。
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.
加文。
回答by lukasgeiter
I'm assuming you use MySQL, it's probably different for other systems
我假设您使用 MySQL,其他系统可能会有所不同
Okay first, the error code for duplicate entry is 1062. And here's how you retrieve the error code from the exception:
好的,首先,重复条目的错误代码是 1062。以下是从异常中检索错误代码的方法:
catch (Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
// houston, we have a duplicate entry problem
}
}
回答by Amirouche Zeggagh
add this code inside class Handler (exception)
在类 Handler 中添加此代码(例外)
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);