Skip to content

[13.x] Add a dedicated validation message for array key failures#60885

Open
nebarg wants to merge 1 commit into
laravel:13.xfrom
nebarg:array-keys-validation-message
Open

[13.x] Add a dedicated validation message for array key failures#60885
nebarg wants to merge 1 commit into
laravel:13.xfrom
nebarg:array-keys-validation-message

Conversation

@nebarg

@nebarg nebarg commented Jul 24, 2026

Copy link
Copy Markdown

Summary

The validator array rule accepts an optional set of allowed keys such as Rule::array(['key_1', 'key_2']), or the string form array:key_1,key_2. When the posted value is an array but contains a key outside the given acceptable list, it currently fails with a generic message:

The foo field must be an array.

This is misleading; the value is an array. This PR gives that specific failure its own array_keys message that names both the allowed and the offending keys:

The foo field must only contain the following keys: key_1, key_2. Unexpected: key_3.

Details

  • Works for both Rule::array([...]) and the string array:key_1,key_2 form (they resolve to the same rule).
  • Customisable under the array_keys key (such as foo.array_keys), exposing :values (allowed keys) and :unexpected (offending keys); either can be used on its own or both omitted entirely.

Backwards compatibility

The new message replaces the old one only for the case it describes, an array containing unexpected keys. Every other array failure keeps the existing message:

  • A non-array value still fails with "must be an array".
  • An array rule used without keys still fails with "must be an array".

$validator->failed() continues to record the failure under the array rule, so nothing that inspects the failed rules changes. The only behavioural change is the wording of that one failure case. Apps that have published language files should add the new array_keys line, and any custom message for this case can move to the array_keys key.

When the "array" rule is given a set of accepted keys and rejects a genuine
array because of an unexpected key, report it with a specific "array_keys"
message that lists the accepted (:values) and unexpected (:unexpected) keys,
instead of the misleading "must be an array" message. The failure is still
recorded as the "array" rule, so failed() is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant