Skip to content

Rules with numeric keys do not validate properly #51499

Closed
@Tofandel

Description

@Tofandel

Laravel Version

10.48.10

PHP Version

8.3

Database Driver & Version

No response

Description

Numeric rules (Eg: [4 => 'required', 8 => 'required']) when added to a validator are not saved properly, they are transformed into[0 => 'required', 1 => 'required'] in the constructor

I tracked it down to this line

$this->rules = array_merge_recursive(
$this->rules, $response->rules
);

It seems the array merge recursive treats any numeric key differently and just appends it to the array instead of preserving the keys, this is explained in the php doc, but undesirable behavior in this case https://www.php.net/manual/en/function.array-merge-recursive.php

array_merge_recursive([], ['foo' => 'required', 4 => 'required', 8 => 'required']);
= [
    "foo" => "required",
    0 => "required",
    1 => "required",
  ]

Steps To Reproduce

Running the following in a tinker session is enough to reproduce

Validator::validate(['foo' => 'baz', 4 => 'foo', 8 => 'baz'], ['foo' => 'required', 4 => 'required', 8 => 'required']);

Results in

   Illuminate\Validation\ValidationException  The 0 field is required. (and 1 more error).

A possible solution is a different implementation of the array_merge_recursive as seen here https://www.php.net/manual/en/function.array-merge-recursive.php#106985

Prior attempt at a fix #39368

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions