I have a simple form with three fields: "name" that is required, "website" that is optional and is a URL, and finaly "email" that is also optional and is an email.
In my rules method of my FormRequest I defined my rules according to Laravel documentation like that:
return [
'name' => 'required',
'website' => 'sometimes|url',
'email' => 'sometimes|email'
];
But whatever I try the result is always the same, i got errors telling me that my url and my email are invalid, when i submit my form without them.
Note: I think that it is more suitable to test the rules only if the input value is not null and not an empty string. Cause for example in my case, url and email rules are playing also the same role as the required rule, while if I need them to be mandatory I'd use the required rule with them
Are you using the ConvertEmptyStringsToNull middleware?
From the Laravel docs
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list
Since 'email' and 'website' are part of the form, they are "present in the input array", unless you're doing something to remove them. They may be empty or null, but the key is still present. Therefore, they will be treated as required.
You should be able to get the results you want using 'url|nullable' and 'email|nullable'.
Thank you @ntzm and @devcircus
The @devcircus solution worked for me.
Most helpful comment
From the Laravel docs
Since 'email' and 'website' are part of the form, they are "present in the input array", unless you're doing something to remove them. They may be empty or null, but the key is still present. Therefore, they will be treated as required.
You should be able to get the results you want using 'url|nullable' and 'email|nullable'.