Laravel how to create a unique rule, excluding space or null

I have a user model that should have unique email addresses, but I also want them to remain empty if the user does not have email ... I see in docs there is a way to make the rule unique and the exception to id ... but I’m not sure how to make it valid or empty, but unique if it isn’t, Sorry, it seems that it’s simple, but I can’t come up with an answer.

public static $adminrules = 'email' => 'email|unique:users,email,null,id,email,NOT_EMPTY' ); 

Edit It is possible that using a rule without required sufficient, because a space or zero will pass validation in these cases. I may have a related error due to which I cannot add more than one empty letter, so I cannot verify this.

  public static $adminrules = 'email' => 'email|unique:users' ); 
+5
source share
1 answer

You should try the following:

 $v->sometimes('email', 'email|unique:users,email', function($input) { return !empty($input->email); }); 

$ v is your validator object, and you basically say that if the email field is not empty, it should also be unique (there shouldn't be any user table entries with this value in the email column).

0
source

All Articles