Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5. Exceptions Handler / unique database field

I want to avoid the following error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

This is displayed on my screen when I try to add an email which already exists in the database. So I want to replace this error screen with a customized error message displayed in a view.

This is what I tried:

//inside app/Exceptions/Handler.php

public function render($request, Exception $e)
{  
    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    }                

    if ($e instanceof Illuminate\Database\QueryException){
        if($e->errorInfo[1] == 1062){
            // But It never reaches this point
        }
    }

    return parent::render($request, $e);
}

The error code is indeed 1062, but the problem is that it does not pass this:

if ($e instanceof Illuminate\Database\QueryException)

Do you know why, or what I am doing wrong?

like image 723
paulinho Avatar asked Mar 16 '26 19:03

paulinho


2 Answers

If nothing works the worst answer is to remove the unique key from 'email' field in db.

But I think what you need is validation, also you can set custom error message for each fields.

reference: http://laravel.com/docs/5.0/validation#custom-error-messages

Controller file

public function store(Request $request)
{
    $v = Validator::make($request->all(), [
            'name' => 'required|min:5',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6',
            'confirm_password' => 'required|min:6|same:password'
        ]);

    if ($v->fails())
    {
        return redirect()->back()->withErrors($v->errors());
    }

    //do success actions here
}
like image 79
Rameez Rami Avatar answered Mar 18 '26 09:03

Rameez Rami


You are looking for 23000 Error code (integrity_constraint_violation). If you take a look at [QueryException][1] class, it extends from [PDOException][2], so you can access to $errorInfo variable.

To catch this error, you may try:

try {
  // ...

} catch ( \Illuminate\Database\QueryException $e) {
    var_dump($e->errorInfo );
}

// example output 
array (size=3)
   0 => string '23000' (length=5)
   1 => int 1452
   2 => string 'Cannot add or update a child row: a foreign key constraint fails (...)'