Optional Fields in Laravel
By default, Laravel includes the TrimStrings
and ConvertEmptyStringsToNull
middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel
class. Because of this, you will often need to mark your "optional" request fields as nullable
if you do not want the validator to consider null
values as invalid. For example:
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]);
In this example, we are specifying that the publish_at
field may be either null
or a valid date representation. If the nullable
modifier is not added to the rule definition, the validator would consider null
an invalid date.
Example Field validation, not required but unique:
Add the nullable validation rule too. This way it will validate it if there is something there, but allow an empty value too.
$this->validate($request, [
'emailaddress' => 'nullable|email|unique:contacts'
]);