Reputation: 28861
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?
Upvotes: 1
Views: 4274
Reputation: 2165
Use this custom fucntion in your validation of input like this example
$validator = Validator::make(Input::all(), [
'name' => 'required',
'email' => [
'required',
'email',
function ($attribute, $value, $fail) {
if (Employee::where('email',$value)->count() > 0) {
$fail($attribute.'already exits');
}
},
],
]);
Upvotes: 1
Reputation: 1048
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
Upvotes: 1
Reputation: 2187
Or simply prevent multiple submission of that same form by disabling the submit button on the client side... It is unlikely that you will get the same email address from two sessions submitted simultaneously...
$(document).ready(function () {
$('#button').click(function () {
$('#button').attr('disabled', true);
$('#Form').submit();
return true;
});
});
You can do something like this server side by generating a token for the form and saving that token to the session locking that form into only one submission... Many ways to skin that cat. The previous answer works as well but you need a round trip to the database... This one has no performance penalty (although this is a fringe case and should be negligeable...)
Hope this helps
Upvotes: -1