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'
);
use Illuminate\Validation\Rule; Validator::make($data, [ 'email' => [ 'required', Rule::unique('users')->ignore($user->id), ], ]);
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.
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.
I tried this. Adding 'nullable' before 'sometimes'.
$validator = Validator::make($request->all(), [
'email' => 'nullable|sometimes|unique:users',
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With