Laravel 5. Exceptions Handler / unique database field

时间:2015-11-12 11:07:30

标签: php laravel exception laravel-4 laravel-5

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?

3 个答案:

答案 0 :(得分:1)

  

如果没有效果,最糟糕的答案是从db。中的'email'字段中删除唯一键。

但我认为您需要的是验证,您也可以为每个字段设置自定义错误消息。

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

控制器文件

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
}

答案 1 :(得分:1)

您正在寻找23000 Error code (integrity_constraint_violation)。如果您查看[QueryException] [1]类,它会从[PDOException] [2]延伸,因此您可以访问$errorInfo变量。

要捕获此错误,您可以尝试:

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 (...)'

答案 2 :(得分:0)

问题参考代码中的命名空间似乎格式不正确。

而不是 Illuminate\Database\QueryException

它应该是 \Illuminate\Database\QueryException