Laravel rule for unique excluding blank or null
Asked Answered
P

4

9

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'                             
); 
Pinder answered 11/6, 2015 at 21:54 Comment(1)
is this where the 'sometimes' rule would be useful?Pinder
C
7

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

 $validator = Validator::make($request->all(), [
        'email' => 'nullable|sometimes|unique:users',
    ]);
Copyhold answered 24/5, 2021 at 18:48 Comment(0)
H
0

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

Handmaid answered 12/6, 2015 at 8:27 Comment(0)
P
0

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'
Pericarp answered 8/3, 2021 at 11:36 Comment(0)
A
0

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'
     ]
   );
}
Agnomen answered 8/9, 2021 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.