Skintest
Skintest

Reputation: 174

Laravel validation not required but still comes back as if it is required

Having some slight issues with laravel validation rules. I.e. I have setup a form with a field name of 'url'. This url needs to be a URL but is not required.

So I have:

'url' => 'url',

In the validation rules, but it still comes back on submit that the URL is an invalid format. But I didn't fill it out and it isn't required.

Slightly confused here, anything I should look out for here?

Upvotes: 4

Views: 4247

Answers (2)

Fariz Keynes
Fariz Keynes

Reputation: 62

For that, I usually use nullable in the very beginning

'url' => 'nullable|url',

Upvotes: -1

ceejayoz
ceejayoz

Reputation: 180004

https://laravel.com/docs/5.6/validation#a-note-on-optional-fields

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.

So, this validation rule will do the trick:

'url' => ['nullable', 'url']

Upvotes: 9

Related Questions