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

mstnorris's avatar

Laravel 5.4 - Correct Validation rule for a required parameter that can be zero

I'm trying to validate a request to load stock into a table. Up until now stock has always had a positive value and the following validation rule worked exactly as expected:

[
    "value" => "required|integer|min:0"
]

Stock is stored and can have multiple values and now stock can have a value of zero (0), I don't think it works with the 'required' rule.

I have changed it to use 'present' which I thought should suffice however it still fails, and adding 'nullable' also doesn't work:

[
    "value" => "present|integer|min:0"
]

Are there validation rules to specify that a field must be present but the value can be zero?

0 likes
1 reply
mstnorris's avatar
mstnorris
OP
Best Answer
Level 55

So the issue actually is with my use of $request->intersect(...) in that it treats keys with a value of zero (0) as false and therefore removes them from the request data array.

For anyone else who may encounter this issue, here is the solution to treat zero (0) values as truthy while; null values, empty strings, and false will be treated as false.

Nb. $params, $rules, and $messages are arrays. See https://laravel.com/docs/5.4/validation#manually-creating-validators for more information.

return \Validator::make(array_filter($request->only($params), function($param) {
    // This is needed to strip out empty values but treat zero (0) as truthy (default array_filter behaviour is
    // to treat zero (0) as false) but we want these values to be present in the validated request data array as
    // zero (0) in the context of a denomination is valid now that we will hold unactivated stock in the Vault.
    return ($param !== null && $param !== false && $param !== '');
}), $rules, $messages);

Please or to participate in this conversation.