Laravel array\_keys Validation Rule (Laravel 13.24) | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. [Laravel](https://www.msaied.com/public/articles?category=laravel)
6. /
7. Reject Unexpected Array Keys with Laravel Validation (Laravel 13.24)

   [Laravel](https://www.msaied.com/public/articles?category=laravel) [Tips &amp; Tricks](https://www.msaied.com/public/articles?category=tips-tricks) 

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

 Laravel 13.24 introduces the `array\_keys` validation rule, letting you whitelist exactly which keys an array may contain and surface a clear error message that names the offending keys.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 5 Aug 2026 · Updated 7 Aug 2026 · 3 min read

ShareCopy linkCopied

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

  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)

 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)*

- [Laravel](https://www.msaied.com/public/articles?search=Laravel)
- [Validation](https://www.msaied.com/public/articles?search=Validation)
- [Laravel 13](https://www.msaied.com/public/articles?search=Laravel%2013)
- [Form Request](https://www.msaied.com/public/articles?search=Form%20Request)
- [API](https://www.msaied.com/public/articles?search=API)

 Frequently asked questions 
---------------------------

  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.

   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'\])\]`.

   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.

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

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

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleValidate and Convert HEIC Images in Laravel 13.24](https://www.msaied.com/public/articles/validate-and-convert-heic-images-in-laravel-1324) [Next articleExtract an Image's Dominant Color in Laravel 13.24](https://www.msaied.com/public/articles/extract-an-images-dominant-color-in-laravel-1324)  

   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)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
