I have a Laravel 8 project where users are expected to verify their emails. Verified emails must be unique. That means no one should be able to register with an email address if someone else has already verified that they own that address (users.email_verified_at
is not NULL
). However if no one has yet verified the email address then multiple user records for the email address are allowed.
Earlier iterations did not fully implement this and contained a simple unique constraint in the migration:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique();
// ...
});
As well as for the validator for user registration:
Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
// ...
]);
The obvious issue with this is that if a malicious person spams the registration form they can block legitimate users from being able to register with their preferred email addresses. So I modified the validation rules as such:
Validator::make($data, [
'email' => [
'required', 'string', 'email', 'max:255',
Rule::unique('users')->where(function ($query) {
return $query->whereNotNull('email_verified_at');
})
],
// ...
]);
This does what is required on the app layer, however it will lead to DB exceptions being thrown unless the unique constraint is removed from the users table:
Schema::table('users', function (Blueprint $table) {
$table->dropUnique('users_email_unique');
});
My question is therefore: