Laravel 13.24 New Published on

Restricting an array's keys with array_keys

A validation rule for “this array only contains these keys”: no more closure comparing array_keys() to a list.

Topics covered: Validation

New in Laravel 13.24. To reject an array that contains unexpected keys, you needed a closure comparing array_keys() to a list. You could also misuse array:column,direction, whose error message (“must be an array”) doesn't say what's wrong. The array_keys rule says exactly that: this array may only contain these keys.

Before

'sort' => ['sometimes', 'bail', 'array', function (string $attribute, mixed $value, Closure $fail) {
    if (array_diff(array_keys($value), ['column', 'direction']) !== []) {
        $fail('The :attribute field may only contain the keys column and direction.');
    }
}],

Since Laravel 13.24

'sort' => ['sometimes', 'array', Rule::arrayKeys(['column', 'direction'])],
// or: 'array_keys:column,direction'

The keys remain optional: to require them, there is required_array_keys.

Your task

In ArticleController, replace the closure with the array_keys rule. Sorting and rejecting an unknown key must not change. The “Requests” tab offers both cases.

Where the feature comes from: the original pull request.