php - Laravel 5. 异常处理程序/唯一数据库字段

标签 php laravel exception laravel-4 laravel-5

我想避免以下错误:

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

当我尝试添加数据库中已存在的电子邮件时,屏幕上会显示此信息。所以我想用 View 中显示的自定义错误消息替换此错误屏幕。

这是我尝试过的:

//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);
}

错误码确实是1062,但是问题是没有通过这个:

if ($e instanceof Illuminate\Database\QueryException)

你知道为什么,或者我做错了什么吗?

最佳答案

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

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

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

Controller 文件

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
}

关于php - Laravel 5. 异常处理程序/唯一数据库字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670050/

相关文章:

php - 如果存在则按另一个表列排序

php - 连接 2 个表的 PDO Sql 查询返回一行

php - Symfony 2 和 Twig 缓存——它们是一样的吗?

php - 从单个查询中解析多个 $variable 值?

php - 逃离刀锋

laravel - VueJS 与 Laravel 的实际使用

c# - 如何在库实现中冒泡/处理 C# 异常

laravel - 如何在一个应用程序中多次登录,例如 Laravel 中的管理员和员工

java - Controller 级别的两个 try catch block

java - 错误 : Could not find or load main class- Novice