Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel rule for unique excluding blank or null

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'                             
); 
like image 200
Phil Avatar asked Jun 11 '15 21:06

Phil


People also ask

How do I ignore unique validation in laravel?

use Illuminate\Validation\Rule; Validator::make($data, [ 'email' => [ 'required', Rule::unique('users')->ignore($user->id), ], ]);

Is unique validation in laravel?

Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table.

What is bail rule in laravel?

If you added more than one validation on your field like required, integer, min and max then if the first is fail then the other should stop to display an error message. right now by default, it prints others too. so you can prevent that by using the bail validation rule in laravel.


1 Answers

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

 $validator = Validator::make($request->all(), [
        'email' => 'nullable|sometimes|unique:users',
    ]);
like image 100
Fabi Ampuero Avatar answered Sep 18 '22 08:09

Fabi Ampuero