Validation reorders items inside nested array when nullable rule precedes required rule #55960
Replies: 3 comments
-
while i dont have a full explanation for why its happening / how to fix it i dont think your expected response is correct from your example it shows that the data is being converted from a "regular" array (which has a defined order) into an associative array (which doesnt) the actual expected result to preserve the order would be
|
Beta Was this translation helpful? Give feedback.
-
This issue relates to how Laravel parses validation rules. In your example, Laravel processes the rules in the following way: {
"array": [
"required",
"array"
],
"array.0.optional": [
"nullable",
"string"
],
"array.1.optional": [
"nullable",
"string"
],
"array.0.required": [
"required",
"string"
],
"array.1.required": [
"required",
"string"
]
} First, Laravel checks for Next, it searches for As a result, the output is exactly what you're seeing: {
"array": {
"1": {
"optional": "optional",
"required": "required2"
},
"0": {
"required": "required1"
}
}
} You can refer to the https://github.com/laravel/framework/blob/12.x/src/Illuminate/Validation/Validator.php |
Beta Was this translation helpful? Give feedback.
-
Thank you for the detailed explanation. I read the code of the The issue occurs in the When The core issue: The order of rules in Would this be considered a bug worth fixing, or should developers expect to handle this behavior in their applications? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Laravel Version
12.16.0
PHP Version
8.4
Database Driver & Version
No response
Description
When a
FormRequest
validates an array of objects where each element contains both a nullable field and a required field, the validator reorders the outer array if the nullable rule is declared before the required rule.In the example below,
$request->validated()
returns the items in a different order from the input: any element that includes the optional field is moved ahead of elements that omit it.Reversing the rule order (
required
first, thennullable
) preserves the original order.This unexpected reordering breaks code that relies on the positional integrity of the array—for example, bulk DB inserts or any logic that matches items by index.
Expected:
The validator should leave the outer array in the same order it was received, regardless of rule declaration order.
Actual:
The outer array is reordered whenever the nullable rule precedes the required rule.
Steps To Reproduce
Controller and FormRequest are defined as follows:
To reproduce, send the following request:
Expected response:
Actual response:
Beta Was this translation helpful? Give feedback.
All reactions