Laravel rule for unique excluding blank or null

10.2k Views Asked by At

I have a user model that needs to have unique email addresses but I also want to allow them to be left blank in case the user has no email...I see in docs there is a way to make a rule for unique and an exception for an id...but I'm not sure how to make this allow null or blank but unique if it is not. Sorry seems like this is simple but I can't think of the answer.

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

Edit It may be that using the rule without required is enough since a blank or null would pass validation in those cases. I might have a related bug that making it so I can't add more than 1 blank email, so I can't verify this.

public static $adminrules = 
    'email' => 'email|unique:users'                             
); 
4

There are 4 best solutions below

0
On

You should try this:

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

$v is your validator object and you basically say that in case the email field is not empty it should also be unique (there shouldn't be a users table record with this value in email column).

0
On

I tried this. Adding 'nullable' before 'sometimes'.

 $validator = Validator::make($request->all(), [
        'email' => 'nullable|sometimes|unique:users',
    ]);
0
On

You should try to change your structure of database to make the field email is nullable. And in the rules try this :

$this->validate($request,
  [
    'email' => 'email',
  ]
);

if(isset($request->address))
{
   $this->validate($request,
     [
       'email' => 'email|unique:users'
     ]
   );
}
0
On

In your Requests/UserRequest you'd have something like

public function rules()
{
    return [
        'email' => [
            'nullable',Rule::unique((new User)->getTable())->ignore($this->route()->user->id ?? null)
         ]
    ];
}

The usage of nullable is what allows the field to be nullable. The other part is to check if the email is unique in the User model table.

If you wish to validate if the field is unique

  • between two fields please refer to this answer.

  • in another table, then add the following to your rules

'exists:'.(new ModelName)->getTable().',id'