Laravel catch Eloquent Unique field error
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
}
}
Laravel Eloquent, how to handle UNIQUE error?
In the general case you should be dealing with database errors using the error code and not any regex.
In your particular case pre-querying or using a Laravel method that does that automatically for you, might be preferable if your intention is to overwrite/update existing data.
If you want to generally anticipate an error and handle it you should do something like:
try {
$foo = new Foo(['foo' => 42, 'bar' => 1]);
$foo->save();
} catch (\Exception $e) { // It's actually a QueryException but this works too
if ($e->getCode() == 23000) {
// Deal with duplicate key error
}
}
Refer to https://dev.mysql.com/doc/refman/5.5/en/error-reference.html for an exhaustive list of error codes (but ideally you'd only need to deal with a couple of specific errors and under very specific circumstances. Lastly the SQL ON DUPLICATE KEY UPDATE
might also work for you, however if you are doing this to silently ignore the new values then I suggest you do the error handling instead.
How to handle QueryException for duplicate entries in Laravel
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 :) Laravel Eloquent Catch Special Expection
You've to wrap your database operation into a try-catch
block and catch the error and do something else when you get a error, maybe redirect with old input data with a error message.
The error code for duplicate entry is 1062. So if you get 1062 as error code that means this data is a duplicate entry. Here is the code look like for catching this exception.
try {
$data = Model::create(array(
'templateURL' => 'some value ',
));
} catch (Illuminate\Database\QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
// we have a duplicate entry problem
}
}
Or if you wish not to handle the exception yourself, you can take help of Laravel Validator. Like following in your controller// validation rules
$rules = array(
'templateURL' => 'unique:YourTableNameHere'
);
$validator = Validator::make(Input::all(), $rules);
// check if the validation failed
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect user back to the form with the errors from the validator
return Redirect::to('form')
->withErrors($validator);
} else {
// validation successful
$data = Model::create(array(
'templateURL' => 'some value ',
));
}
Then in your view template you can access the error messages via $errors
variable.Learn more about validation there https://laravel.com/docs/5.3/validation
Try catch for laravel is not working for duplicate entry
You need to make Exception as global,
Either by using.
use Exception;
catch(Exception $exception)
Or by using
catch(\Exception $exception)
catch(Exception $exception)
Laravel validation throws error on updating same unique value
You have to use following code
$this->validate($request, [
'name' => ['required', Rule::unique('myTableName')->ignore($yourVariable->id)],
]);
Add header section below codeuse Illuminate\Validation\Rule;
More Details here
Related Topics
PHP Readfile() and Large Files
Add Some Attribute Values to Woocommerce Variable Product Title from Chosen Variation
MySQL Insert ....On Duplicate Update - Adds One to the Autoincrement
Composer:How to Add a Dependency Without Network Connection
Find Windows 32 or 64 Bit Using PHP
File_Get_Contents() Failed to Open Stream:
File_Get_Contents() Failed to Open Stream:
How to Encrypt HTML Source Code Output Using PHP
How to Use Laravel Passport with a Custom Username Column
Newline Not Working in PHP Mail
Get First Element in PHP Stdobject
Remove "(Optional)" Text from Checkout Fields in Woocommerce 3.4+
When Do/Should I Use _Construct(), _Get(), _Set(), and _Call() in PHP
How to Get an Array of Data from $_Post
PHP Date Function Seven Days Previous
Remove "(Optional)" Text from Checkout Fields in Woocommerce 3.4+