Superhasi's avatar

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

Hey all, i try to make my first steps with laravel. Now i am at a point where i get angry :-) I try to use the eloquent save method... In my database i have a unique constraint over 3 columns. When i save a "really new" entry then everything is well. When i save an existing one (testing), it fails -> which is ok -> but i want to catch this error and display it in my application by my own. Instead of this i always get the "Whoops, looks like something went wrong." page. I don't want this page to be displayed.

How can i intercept the SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry error and display it by my own?

Thanks in advance and sorry for my bad english...

0 likes
5 replies
christophrumpel's avatar

Hey, what about a try catch blog like that:

...
try
{
     // do your query here
}
//catch specific exception....
catch(QueryException $e)
{
    // do sthg when the error occurs
}
Superhasi's avatar

Hey,

at first thanks for your reply... I've tried it already before my post. Same result!

I get in the Laravel "Whoops Page" 2 errors. PDOException and QueryException.

Can it be an "easy" configuration mistake from me?

Superhasi's avatar

Hey guys,

i get this in "Whoops" errorpage:

QueryException in Connection.php line 669: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY' (SQL: insert into intervals (ID, updated_at, created_at) values (1, 2016-03-26 07:00:15, 2016-03-26 07:00:15))

This is the PHP code:

$test = new App\Models\Interval\Interval();     // Eloquent Model with PK ID
        $test->ID = 1;                              // Set existing ID
        try{
            $test->save();                              // Try to save (with error!) because ID exists
        } catch(PDOException $e)
        {
        echo "error";                           // catch this error
        }

The ID 1 is existing... It's for testing purpose. I want to get back an "SQL" error and display this by myself (turning off the "Whoops" error page) Environment is production. Even if i set debug to true or false this errorpage comes up.

Any ideas?

moharrum's avatar
Level 6

This happens because you are trying to catch a PDOException and PHP is throwing a QueryException.

try{
    do_someting();
} catch(QueryException $e) {
    echo "ERROR";
}

Just to be safe, you can catch any descendant of Exception instead:

try{
    do_someting();
} catch(\Exception $e) {
    echo "ERROR";
}

Please or to participate in this conversation.