framework: [5.4] Validation Rule nullable with required failed (not expected)

  • Laravel Version: 5.4.16
  • PHP Version: 7.0.15
  • Database Driver & Version: -

Description:

In Laravel 5.4.15 the following test is valid:

$rules = ['id' => 'required|nullable'];
$data = ['id' => null];
$this->validate($data, $rules);

In Laravel 5.4.16 the same code is invalid - so all my unit tests failed. I think this is not the correct behaviour, because the key id is in the data and the ruleset needs a key id and allows being null - that it is.

Steps To Reproduce:

$rules = ['id' => 'required|nullable'];
$data = ['id' => null];
$this->validate($data, $rules);

in unit test or in command line (tinker)

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 2
  • Comments: 16 (4 by maintainers)

Most upvoted comments

@LasseHaslev I am having this same issue. However, I discovered that there is a present validation rule that checks the field exists in the input data, but can be empty.

Ok, but technically I think your decision is wrong. I will change my code.

In a recent change we made null invalid in a required rule, the old behaviour was reported multiple times as a bug, when you say a field is required then it doesn’t really make sense to accept null as a value for that field. May I ask what’s the use case?

@brandonferens Thank you!

Changed my code from this

if (! request()->has('data')) {
    request()->validate([
        'data' => 'required',
    ]);
}

request()->validate([
    'data' => 'nullable',
]);

To this

request()->validate([
    'data' => 'present',
]);

And all my test are still working! 👍

In a recent change we made null invalid in a required rule, the old behaviour was reported multiple times as a bug, when you say a field is required then it doesn’t really make sense to accept null as a value for that field. May I ask what’s the use case?

In a case of nullifying required nullable field, in other words updating its value to NULL, it is very useful to have option to have both rules available in combination. I wonder in which case these two rules look like a bug. Combined they clearly say: “Field must have value or be null”. Null is a value too, unknown, but a value. To me, it sounds much more like a bug to specify that a field is nullable, and have that ignored.

There are workarounds ofc, but this looks like a no brainer to me.

In my use case I have to have a field in the data with a key. But null is a valid value, like an integer too.