Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

php - Laravel catch Eloquent "Unique" field error

I am trying to identify when inserting a record using eloquent in Laravel when it throws an exception because of a unique field error.

The code I have so far is:

try {

    $result = Emailreminder::create(array(
                       'user_id' => Auth::user()->id,
                       'email' => $newEmail,
                       'token' => $token,
              ));

} catch (IlluminateDatabaseQueryException $e) {
    return $e;
}

It throws an exception OK I just don't know what to do to identify it as a column duplicate error?

Thanks,

Gavin.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm assuming you use MySQL, it's probably different for other systems

Okay first, the error code for duplicate entry is 1062. And here's how you retrieve the error code from the exception:

catch (IlluminateDatabaseQueryException $e){
    $errorCode = $e->errorInfo[1];
    if($errorCode == 1062){
        // houston, we have a duplicate entry problem
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...