Framework: [5.4] Validator rules failing when using ConvertEmptyStringsToNull middleware

Created on 26 Jan 2017  路  4Comments  路  Source: laravel/framework

  • Laravel Version: 5.4
  • PHP Version: 7.1.0
  • Database Driver & Version: MySQL 5.5.5

Description:

When using the new ConvertEmptyStringsToNull middleware, validator rules will fail for empty fields.

Steps To Reproduce:

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.

Most helpful comment

@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');
}

All 4 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

easmith picture easmith  路  69Comments

mnpenner picture mnpenner  路  72Comments

JosephSilber picture JosephSilber  路  176Comments

Xerotherm1c picture Xerotherm1c  路  70Comments

astr0naugh7 picture astr0naugh7  路  65Comments