Laravel 5 Validation: A Unique Rule for Examining Emails

For testing and support, I want one or two letters to be used several times in my user database. All other emails must be unique. For instance:

"email" => "required|email|unique:users,email,admin@test.de"

This does not work, and I cannot use the id field to exclude, because there will be multiple entries with the same email address.

+4
source share
2 answers

Sounds like a case for sometimes

$whitelist = ['admin@test.de', 'foo@bar.com', 'etc@etc.com'];
$validator->sometimes('email', 'unique:users', function($input) use ($whitelist){
    return ! in_array($input->email, $whitelist);
});

Meaning if the email address is not listed in the white list, the rule applies unique.


Inside the form request, you can add material to the validation instance by overriding getValidatorInstance():

protected getValidatorInstance(){
    $validator = parent::getValidatorInstance();
    $validator->sometimes(...);
    return $validator;
}
+3

, XX - .

"email" => "required|email|unique:users,email,XX,id"

PS ,

0

Source: https://habr.com/ru/post/1584508/


All Articles