如何处理 Laravel 中重复条目的 QueryException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45893359/
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
How to handle QueryException for duplicate entries in Laravel
提问by Mithun Shreevatsa
Here is my model code trying to handle duplicate entries
:
这是我尝试处理的模型代码duplicate entries
:
$userData = ['name' => $name, 'email' => $email, 'password' => $password];
public function addUser($userData) {
try {
DB::table('users')->insert($userData);
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
throw ('Duplicate Entry');
}
}
}
Calling controller code looks like: $userModel->addUser($userData);
调用控制器代码如下所示: $userModel->addUser($userData);
Here I am not trying to print any response received from model
.
在这里,我不是要打印从model
.
Getting error as:
获取错误为:
What am I doing wrong? How to handle Exceptions correctly and what's the best practise of doing it?
我究竟做错了什么?如何正确处理异常以及这样做的最佳实践是什么?
回答by Mithun Shreevatsa
I was very near to my answer, it was all about namespace
issue and error display issue:
我非常接近我的答案,这完全是关于namespace
问题和错误显示问题:
Illuminate\Database\QueryException $e
should be:
\Illuminate\Database\QueryException $e
Illuminate\Database\QueryException $e
应该:
\Illuminate\Database\QueryException $e
try {
DB::table('users')->insert($userData);
} catch(\Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == '1062'){
dd('Duplicate Entry');
}
}
return
and throw
for error did not work, but 'dd' method worked. So this saves my time in querying twice to identify the duplicates and insert and am happy for it :)
return
和throw
错误没有用,但 'dd' 方法有效。因此,这节省了我两次查询以识别重复项并插入的时间,并为此感到高兴:)
回答by AddWeb Solution Pvt Ltd
You should try this:
你应该试试这个:
public function addUser($userData)
{
try {
DB::table('users')->insert($userData);
} catch (Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
return 'Duplicate Entry';
}
}
}
For more details, please follow this link.
欲了解更多详情,请点击此链接。
回答by Waiyl Karim
If you just want to avoid the duplicate entry exception without having to wrap everything between try{} catch{}
, you could simply use Laravel's firstOrCreate()
method as follows:
如果您只想避免重复条目异常而不必在 之间包装所有内容try{} catch{}
,您可以简单地使用 Laravel 的firstOrCreate()
方法,如下所示:
User::firstOrCreate([
'email' => $request->email // unique field here
], $userData);
Using this method assumes that you are calling protected $guarded = []
on your User model.
使用此方法假定您正在调用protected $guarded = []
您的 User 模型。