Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

[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);
}
like image 948
Sarath TS Avatar asked Dec 23 '22 10:12

Sarath TS


1 Answers

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.

like image 144
Sarath TS Avatar answered Jan 05 '23 18:01

Sarath TS