Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EliasSoares's avatar

How to catch QueryException?

I'm trying to do this:

try {
    $model_class::destroy($id);
} catch ( Illuminate\Database\QueryException $e) {
    var_dump($e->errorInfo);
}

But when I run this code to force an Exception (Integrity constraint violation), I still getting an debug screen, when the exeption should be catch.

The debug shows me two exceptions:

Illuminate\Database\QueryException and PDOException

If I catch the PDOException, it works. But if I catch QueryException, it does not works.

Why?

BTW, is there any way better to catch Integrity constraint violation exceptions when deleting a row?

0 likes
9 replies
dancourse's avatar

Any news on this one? I can't seem to catch mine either in Laravel 5.0

            try {
                $this->model->create($data);

            } catch (Illuminate\Database\QueryException $e) {
                dd($e);

            } catch (PDOException $e) {
                dd($e);
            }            
1 like
itwonders's avatar

probably is namespace issue

try

catch (\Illuminate\Database\QueryException $e)
10 likes
faruqisan's avatar

i've trying to use the correct namespace but still cant catch the exception any help?

Patryk1098's avatar

@faruqisan You've probably solved this, but make sure you have a \ prefixed to your namespace path for the QueryException class.

2 likes
MisterX25's avatar

This is quite an old thread, but still... it describes EXACTLY the problem I'm facing now and I can't figure it out.

use Illuminate\Database\QueryException;

try {
    $newuser = new User();
    $newuser->save();
    return response()->json(null, 200);
} catch (QueryException $e) {
    $message = "Error";
    return response()->json($message, 500);
}

I get :

{
  "message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'last_name' cannot be null (SQL: insert into `users` ... ",
  "exception": "Illuminate\Database\QueryException",
...
}

btw: catch (Exception $e) also doesn't work

i.e: the exception isn't caught.

It's driving me nuts, help please !

thvs86's avatar

For anyone stumbling on this old thread (like me) and has the same issue, meaning:

catch (Exception $exception)

and

catch (QueryException $exception)

not working - the answer is to try:

catch (PDOException $exception)

after you've of course ruled out namespace issues.

berusjamban's avatar

You can also catch it using this approach:

catch (Throwable $e)

spyworld's avatar

Be careful catching Query Exception. Make sure user can't see the query.

Please or to participate in this conversation.