When using the new ConvertEmptyStringsToNull
middleware, validator rules will fail for empty fields.
Take for example a two input form, asking for the user's name and website URL. The name is required but the URL is optional. When posted, the form validator may look like this:
<?php
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'website-url' => 'url',
]);
dd('Valid data sent');
}
If you submit the form with only a name filled out and a blank website-url
field, the validator will fail saying that the null
value of $request->input('website-url')
is not a valid URL. The validator should not be checking for a valid URL since the field is not required.
If you use this middleware you say that you want to convert all empty strings to null, you'll need to prepare your rules for this change, use the nullable
rule for all optional fields in this case.
@IrsyadAdl You need to add nullable
to your rule set, like this:
<?php
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'website-url' => 'nullable|url',
]);
dd('Valid data sent');
}
Swapping out 'sometimes' for 'nullable' fixed this for me when using the ConvertEmptyStringsToNull middleware
Couldn't find anything in upgrade guide. Glad I found this issue.
Adding nullable
to the rules worked for me!
Most helpful comment
@IrsyadAdl You need to add
nullable
to your rule set, like this: