Laravel array\_keys Validation Rule (Laravel 13.24) | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com) [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles  ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

  [ home ](https://www.msaied.com)    [ articles ](https://www.msaied.com/articles)    Reject Unexpected Array Keys with Laravel Validation (Laravel 13.24)        On this page       1. [  The Problem with Silent Filter Failures ](#the-problem-with-silent-filter-failures)
2. [  Basic Usage ](#basic-usage)
3. [  Why Not array:key\_1,key\_2? ](#why-not-codearraykey-1key-2code)
4. [  Custom Messages with :unexpected ](#custom-messages-with-codeunexpectedcode)
5. [  Real-World Example: Filtered Index Endpoint ](#real-world-example-filtered-index-endpoint)
6. [  Validating a JSON Column on Writes ](#validating-a-json-column-on-writes)
7. [  Key Behaviours to Know ](#key-behaviours-to-know)

  ![Reject Unexpected Array Keys with Laravel Validation (Laravel 13.24)](https://cdn.msaied.com/521/93f8f75335e1366269b4971f40fff6ad.png)

 [  Laravel ](https://www.msaied.com/articles?category=laravel) [  Tips &amp; Tricks ](https://www.msaied.com/articles?category=tips-tricks)  #Laravel   #Validation   #Laravel 13   #Form Request   #API  

 Reject Unexpected Array Keys with Laravel Validation (Laravel 13.24) 
======================================================================

     5 Aug 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said  

       Table of contents

1. [  01   The Problem with Silent Filter Failures  ](#the-problem-with-silent-filter-failures)
2. [  02   Basic Usage  ](#basic-usage)
3. [  03   Why Not array:key\_1,key\_2?  ](#why-not-codearraykey-1key-2code)
4. [  04   Custom Messages with :unexpected  ](#custom-messages-with-codeunexpectedcode)
5. [  05   Real-World Example: Filtered Index Endpoint  ](#real-world-example-filtered-index-endpoint)
6. [  06   Validating a JSON Column on Writes  ](#validating-a-json-column-on-writes)
7. [  07   Key Behaviours to Know  ](#key-behaviours-to-know)

 The Problem with Silent Filter Failures
---------------------------------------

Endpoints that accept a bag of options have a subtle failure mode: a client sends `?filter[stat us]=draft` with a typo, your code reads `$filters['status']`, finds nothing, and returns the full unfiltered list. No error is raised, the response looks correct, and the bug surfaces later as an intermittent mystery.

Laravel 13.24 ships the `array_keys` validation rule to close this gap. It lets you declare exactly which keys an array may contain and returns a failure message that names what went wrong.

Basic Usage
-----------

Both the fluent builder and the string form are supported:

```php
use Illuminate\Validation\Rule;

$request->validate([
    'filter' => Rule::arrayKeys(['status', 'author', 'tag']),
]);

// Equivalent string form
$request->validate([
    'filter' => 'array_keys:status,author,tag',
]);

```

Given `['status' => 'draft', 'stat us' => 'draft']`, validation fails with:

> The filter field must only contain the following keys: status, author, tag.

The keys are **permitted, not required**. To enforce that specific keys must also be present, compose the rule with `required_array_keys`:

```php
'coordinates' => [
    'required_array_keys:lat,lng',
    Rule::arrayKeys(['lat', 'lng']),
],

```

Why Not `array:key_1,key_2`?
----------------------------

`Rule::array()` has accepted a key list for a while, but it conflates two concerns — type checking and key checking — into one message:

| Rule | Message on unexpected key | |---|---| | `array:status,author` | The filter field must be an array. | | `array_keys:status,author` | The filter field must only contain the following keys: status, author. |

The first message is misleading when the value *is* an array. The new rule separates the concerns and reports them independently in `$validator->failed()` as `Array` and `ArrayKeys`.

Custom Messages with `:unexpected`
----------------------------------

The rule ships two placeholders: `:values` (the allowed keys) and `:unexpected` (the keys that caused the failure). The `:unexpected` placeholder is especially useful in API responses:

```php
$request->validate(
    ['filter' => Rule::arrayKeys(['status', 'author', 'tag'])],
    ['filter.array_keys' => 'The :attribute field may not contain :unexpected.'],
);
// The filter field may not contain colour, sort.

```

Real-World Example: Filtered Index Endpoint
-------------------------------------------

```php
class IndexPostRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'filter' => ['sometimes', 'array', Rule::arrayKeys(['status', 'author', 'tag'])],
            'filter.status' => ['sometimes', Rule::enum(PostStatus::class)],
            'filter.author' => ['sometimes', 'integer', 'exists:users,id'],
            'filter.tag'    => ['sometimes', 'string', 'max:50'],
            'sort' => ['sometimes', 'string', Rule::in(['title', '-title', 'published_at', '-published_at'])],
        ];
    }

    public function messages(): array
    {
        return [
            'filter.array_keys' => 'Unknown filter: :unexpected. Allowed filters are :values.',
        ];
    }
}

```

Anything that reaches the controller is a key you explicitly named, so defensive `isset` checks become unnecessary.

Validating a JSON Column on Writes
----------------------------------

The rule is equally useful when persisting a settings or preferences column:

```php
'preferences' => ['sometimes', 'array', Rule::arrayKeys(['theme', 'timezone', 'digest_frequency'])],
'preferences.theme'            => ['sometimes', Rule::in(['light', 'dark', 'system'])],
'preferences.timezone'         => ['sometimes', 'timezone'],
'preferences.digest_frequency' => ['sometimes', Rule::in(['daily', 'weekly', 'never'])],

```

A renamed frontend field now fails loudly during deployment instead of silently writing a stale key into every row.

Key Behaviours to Know
----------------------

- **A non-array value fails the rule.** Pair with `array` so the type failure gets its own message.
- **At least one key is required.** Passing no keys throws an `InvalidArgumentException` at runtime. Use `prohibited` if you want to block the field entirely.
- **Accepts any `Arrayable`.** Collections and backed enums both work: `Rule::arrayKeys(FilterKey::cases())`.
- **Variadic form is supported.** `Rule::arrayKeys('status', 'author')` is equivalent to passing an array.

The rule was contributed by [@nebarg](https://github.com/nebarg) in [\#60918](https://github.com/laravel/framework/pull/60918).

---

*Source: [Reject Unexpected Array Keys with Laravel Validation — Laravel News](https://laravel-news.com/laravel-array-keys-validation-rule)*

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Freject-unexpected-array-keys-with-laravel-validation-laravel-1324&text=Reject+Unexpected+Array+Keys+with+Laravel+Validation+%28Laravel+13.24%29) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Freject-unexpected-array-keys-with-laravel-validation-laravel-1324) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  What is the difference between `array:key\_1,key\_2` and `array\_keys:key\_1,key\_2` in Laravel validation?        Both reject unexpected keys, but `array` reports a single ambiguous message ('must be an array') even when the value is already an array. `array_keys` reports a dedicated message that names the allowed keys, and the two rules fail independently in `$validator-&gt;failed()` so you can handle each case separately. 

      Q02  Does the `array\_keys` rule require all listed keys to be present?        No. It only constrains which keys *may* appear; it does not require any of them. To also enforce presence, combine it with `required_array_keys`: `['required_array_keys:lat,lng', Rule::arrayKeys(['lat', 'lng'])]`. 

      Q03  How can I show the client exactly which unexpected key failed validation?        Use the `:unexpected` placeholder in a custom message: `'filter.array_keys' =&gt; 'The :attribute field may not contain :unexpected.'`. This tells the client the exact key name rather than just the list of allowed keys. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://www.msaied.com/articles) 

 [ ![Livewire v4.4.6 Released: Bug Fixes, Test Improvements, and Alpine v3.17.4](https://cdn.msaied.com/689/454c52282f3ef5d585905e5952ca969c.png) Livewire Laravel Alpine.js 

### Livewire v4.4.6 Released: Bug Fixes, Test Improvements, and Alpine v3.17.4

Livewire v4.4.6 ships with 18 changes including validation performance improvements, better test assertions, k...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 21 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/livewire-v446-released-bug-fixes-test-improvements-and-alpine-v3174) [ ![Laravel 14: New Features, Breaking Changes, and PHP 8.4 Requirement](https://cdn.msaied.com/688/2dfe8f11b0bef35c0ee6db912004209f.png) Laravel 14 PHP 8.4 Breaking Changes 

### Laravel 14: New Features, Breaking Changes, and PHP 8.4 Requirement

Laravel 14 is expected in Q1 2027 and will require PHP 8.4. Here is everything known so far from the master br...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 21 Sep 2026     4 min read  

  Read    

 ](https://www.msaied.com/articles/laravel-14-new-features-breaking-changes-and-php-84-requirement) [ ![Building a Laravel Package: Service Providers, Auto-Discovery, and Config Merging](https://cdn.msaied.com/687/e53f819c8f897c1ad12a1df0661a18f7.png) laravel packages service-providers 

### Building a Laravel Package: Service Providers, Auto-Discovery, and Config Merging

Learn how to build a production-ready Laravel package from scratch — covering service provider design, auto-di...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 21 Sep 2026     1 min read  

  Read    

 ](https://www.msaied.com/articles/building-a-laravel-package-service-providers-auto-discovery-and-config-merging-4) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://www.msaied.com)
- [Projects](https://www.msaied.com/projects)
- [Articles](https://www.msaied.com/articles)
- [Certificates](https://www.msaied.com/certificates)
- [Contact](https://www.msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
