Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

danon-13367735's avatar

How to validate optional integer field?

For various reasons, I decided to not include ConvertEmptyStringsToNull middleware. I want to post optional fields (so I need to know if they're included or not), and I want people to update values to empty strings (so I need to differenciate between empty strings and null), hence I removed ConvertEmptyStringsToNull. I think that because it's a middleware, then it's within acceptable usage of the framework to remove it, right? After all, if it wasn't, why make it a middleware, and not built into the framework? So I decided to remove it.

Now, my use case. I would like a controller, for this particular API:

  • patch('/endpoint', {otherField:'foo'}) - field myNumber is not updated, but otherField is
  • patch('/endpoint', {otherField:''}) - field otherField is updated to ""
  • patch('/endpoint', {myNumber: '12'}) - that updates value to 12
  • patch('/endpoint', {myNumber:'foo'}) - I get 422 validation error, because string is not valid
  • patch('/endpoint', {myNumber:''}) - I want to get 422 validation error here

So basically I have two fields, otherField is text, and myNumber is integer. I want to validate type, I want to respect empty string, and I want them to be optional.

I wrote rules like that: $request->validate(['myNumber' => 'integer']), and it doesn't validate the empty string as invalid (though it should). I tried present, sometimes, required, numeric, and their combinations. I tried using required|integer, but that makes the field, well, required, and I want the field to be optional.

That seams wierd to me, because in Django and RubyOnRails that works just fine.

I found out that there are things like "implicit rules", https:// laravel.com/docs/11.x/validation#implicit-rules and when a field is empty, the laravel simply doesn't validate it. I think the rationale here is that if ConvertEmptyStringsToNull is on, then "empty string" == "missing field", but if you take the middleware out, then that assumption breaks.

What would be the best way to reject an empty string from a field in validation rules, when ConvertEmptyStringsToNull is not added? PS: I know I can add ConvertEmptyStringsToNull back in, but that breaks more stuff for me (including the fact that I can't update field to an empty string if I wish).

0 likes
1 reply

Please or to participate in this conversation.