laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

[Proposal] Validator returns null on items not present in the request. #1734

Open MarGul opened 5 years ago

MarGul commented 5 years ago

The issue that I run in to a lot is that I will have code like this in my controller:

$data = $request->validate([
    'existing_attribute' => 'required',
    'non_existing_attribute' => ''
]);

Meaning that sometimes the attribute non_existing_attribute will be present in the request but sometimes it won't. But because I will use the $data variable in further processing, in say for example a ServiceClass I need to do things like this:

$data['non_existing_attribute'] = $data['non_existing_attribute'] ?? null;

What I am proposing is that the validator will return all the keys that you entered into the validate method but the one's that are not present in the request will be set to null.

This could be fixed by removing the if statement on Line 341 in Validator.php and replacing it with:

Arr::set($results, $key, $value !== $missingValue ? $value : null);

Haven't looked at any implications here so I opened this proposal first and if people think it sounds good and don't have any side-effects I'll open a pull-request.

michaeldyrynda commented 5 years ago

So the nullable or sometimes rules not solve this issue for you?

MarGul commented 5 years ago

Thanks for the reply. No it doesn't because the non_existing_attribute is not even present in the request. I could fix this on the front-end by always making sure that the non_existing_attribute is there and is set to null.

I had this problem when I was using sync on a many-to-many. I did add the flag for not deleting records that was not present and it solved it but I just feel like this:

When I have:

$data = $request->validate([
    'field1' => '',
    'field2' => ''
]);

The $data variable should have the keys field1 and field2 even though the request body was empty (not containing field1 and field2). This way I always know that my $data variable will contain the keys that I specified so I don't later on get issues with key do not exists.

Not sure if I just tackle this "problem" on the wrong end. Maybe should be fixed on my front-end to always send the "correct" keys in the request. Just set it to null instead of omitting it completely but the above just feels natural for me.