Search code examples
phpmysqllaravellaravel-5laravel-validation

Duplicate fields despite using unique validation in Laravel 5


In Laravel I have an API which allows users to register.

The registration has a simple validation for emails to be unique and looks something like this:

public function register(Request $request) {
    $this->validate($request, [
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|min:6|max:50',
    ]);

    // create new user and save model
}

Unfortunately, I still found quite a few users in my table with duplicate emails.

I believe the reason for this is that my app sometimes sends same request, multiple times, in quick succession. This means both request passes the validation despite having the same email as they have not been added to the database yet.

How can I fix this issue to ensure uniqueness for emails?


Solution

  • You can use a try-catch block when actually inserting the data (see the PHP Manual for more Information):

    try {
      $connection->query(<yourInsertquery>);
      return true;
    } catch (PDOException $e){
      if ($e->getCode() == 1062){
        return 'duplicate';
      }
      return false;
    }
    

    With this you will get a String 'duplicate' returned whenever you have duplicated entries, otherwise false in case of an different error and true