Allow Empty Values when Validating URL or Email in Laravel


Laravel provides some handy validators for validating URLs and emails. But what, if you have a field, that accepts an optional email or optional URL?

This can be realized by nullable, an example:

$validatedData = $request->validate( [
    'name'        => 'required|max:100',
    'email'       => 'nullable|email',
    'website'     => 'nullable|url'
] );

There is a difference between nullable and sometimes. If you use nullable, the value can be null or empty. If you use sometimes, the validation will be skipped, if the value is not present in the input array. If the value is present but it is null or empty, the validation will not be skipped.