Monday, March 13, 2017

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([
        '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?



via Yahya Uddin

Advertisement