I was curious if there is a way we can check if there is a constraint violation error when delete or insert a record into the database.

引发的异常称为"QueryException",但这可能是一系列错误.如果我们能在异常中判断具体错误是什么,那就太好了.

推荐答案

You are looking for the 23000 Error code (Integrity Constraint Violation). If you take a look at QueryException class, it extends from PDOException, 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 from MySQL
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 (...)'

To be more specific (Duplicate entry, not null, add/update child row, delete parent row...), it depends on each DBMS:

  • PostgreSQLSQL server遵循SQL标准对SQLSTATE代码的约定,因此可以从数组$e->errorInfo[0]返回第一个值,或者直接调用$e->getCode()
  • MySQLMariaDBSQLite不严格遵守规则,因此需要从数组$e->errorInfo[1]返回第二个值

对于laravel来说,处理错误很容易,只需在"app/start/global.php"文件中添加以下代码(或创建一个service provider):

App::error(function(\Illuminate\Database\QueryException $exception)
{
    $error = $exception->errorInfo;
    // add your business logic
});

Laravel相关问答推荐

URL类图中的循环关系

Laravel:如何从不断更新的Controller中分页数据

Laravel Eloquent查询与集合优化

Laravel中如何动态更改路由链接?

使用 laravel 根据当月显示注册用户列表

FileViewFinder.php 第 137 行中的 Laravel 5 InvalidArgumentException:未找到视图 [.admin]

Laravel:转义LIKE子句?

Laravel 5 如何全局设置 Cache-Control HTTP 标头?

Laravel 将 JSON 转换为数组?

Laravel 4,如何测试复选框是否被选中?

在 Laravel Blade 中转义 vue.js 数据绑定语法?

Laravel 生产问题 - 使用 Laravel 4.1.x 更新composer

Laravel 从现有模型生成迁移

如何仅从 laravel FormRequest 中获取经过验证的数据?

如何在 Laravel 中实现数组类型路由?

调用未定义的方法 Illuminate\Foundation\Application::bindShared()

Laravel 搜索关系

如何从 Laravel 中的资源中获取图像?

Distinct values with pluck

如何在 laravel 表单验证错误消息中给出自定义字段名称