phplaravel-5laravel-5.5

Laravel unique email validation is not working on different character case in mongodb


I have a registration form with unique email validation. When I enter different character case, emails does not apply unique validation.

example@gmail.com, Example@gmail.com, eXample@gmail.com: Laravel unique validation is failed.

example@gmail.com, example@gmail.com, example@gmail.com: 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);
}

Solution

  • 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.