Laravel 5.4 sometimes validation rules not working

Munna Khan picture Munna Khan · Feb 4, 2017 · Viewed 7.9k times · Source

I am trying to validate a date field only if it is present. It was working fine before I upgraded from Laravel 5.2 to 5.4

In Laravel 5.2 this rules works fine:

public function rules()
{
    return [
        'available_from' => 'date',
    ];

}

In 5.4 it returns validation error The available from is not a valid date. I tried this new rules

public function rules()
{
    return [
        'available_from' => 'sometimes|date',
    ];

}

Still got the same error and seems the sometimes rules not affecting the validation at all. How can I get rid of this error?

I don't understand why Laravel changed something that was working before!!!

Answer

ikurcubic picture ikurcubic · Feb 4, 2017

The problem occurs because of \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class in Http\Kernel.php.

When you submit empty date field this middleware converts empty string to null. Then validation returns not valid date error. You can check docs for more details.

It can be fixed with nullable

public function rules()
{
    return [
        'available_from' => 'sometimes|nullable|date',
    ];

}

From Laravel docs:

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.