Laravel Catch Eloquent "Unique" Field Error

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,

  1. Either by using.

    use Exception;

and then use

catch(Exception $exception)

  1. Or by using

    catch(\Exception $exception)

Instead of this

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 code

use Illuminate\Validation\Rule;

More Details here



Related Topics



Leave a reply



Submit