guidsen guidsen - 3 months ago 41
PHP Question

Laravel check for constraint violation

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.

The exception thrown is called 'QueryException' but this can be a wide range of errors. Would be nice if we can check in the exception what the specific error is.

Answer Source

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) {

// 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:

  • PostgreSQL and SQL server follow the SQL standard's conventions for SQLSTATE code, so you may return the first value from the array $e->errorInfo[0] or call $e->getCode() directly
  • MySQL, MariaDB and SQLite do not strictly obey the rules, so you need to return the second value from the array $e->errorInfo[1]

For laravel, handling errors is easy, just add this code in your "app/start/global.php" file ( or create a service provider):

App::error(function(\Illuminate\Database\QueryException $exception)
    $error = $exception->errorInfo;
    // add your business logic
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download