Here is my model code trying to handle 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);
Here I am not trying to print any response received from model
.
Getting error as:
What am I doing wrong? How to handle Exceptions correctly and what's the best practise of doing it?
I was very near to my answer, it was all about namespace
issue and error display issue:
Illuminate\Database\QueryException $e
should be:
\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 :)