I have a registration form with unique email validation. When I enter different character case, emails does not apply unique validation.
[email protected], [email protected], [email protected]
: Laravel unique validation is failed.
[email protected], [email protected], [email protected]
: Laravel unique validation is success.
Please check my code below and correct me. Email is storing as lowercase in database.
DB - Mongodb,
Framework - Laravel 5.5
jenssegers/laravel-mongodb is using to connect laravel and mongodb
RegisterController.php
protected function validator(array $data)
{
return Validator::make($data, [
'firstName' => 'required|string|max:255',
'lastName' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:user,usrEmail',
'password' => 'required|string|min:6|confirmed',
]);
}
User.php (Model)
public function setusrEmailAttribute($value)
{
$this->attributes['usrEmail'] = strtolower($value);
}
With the help of laravel custom validation rule I resolved this issue.
I create a new rule using php artisan command php artisan make:rule Lowercase
and defined the rule.
app/Rules/Lowercase.php
public function passes($attribute, $value)
{
return strtolower($value) === $value;
}
public function message()
{
return 'The :attribute must be lowercase.';
}
I have attached the rule object with other rules
RegisterController.php
use App\Rules\Lowercase;
protected function validator(array $data)
{
return Validator::make($data, [
'firstName' => 'required|string|max:255',
'lastName' => 'required|string|max:255',
'email' => [ 'required', 'string', 'email', 'max:255', 'unique:user,usrEmail', new Lowercase ],
'password' => 'required|string|min:6|confirmed',
'dataProtection' => 'required',
'termsService' => 'required',
]);
}
While registration users enter email, system will alert the users to use lowercase.
It works for me I am not sure this a good approach or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With