How to Validate Array Keys in Laravel

January 23rd, 2025 • 2 minutes read time

If you're validating array data where the keys are significant and require validation, it's not immediately obvious how this can be achieved in Laravel.

Let me show you how.

Imagine you're working with the following data structure being submitted and picked up by a controller:

[
    1 => ['email', 'sms'],
    2 => ['email'],
]

In this example, the keys are unique IDs for notification types in our database. Let's roll with this example while we look at how to validate these array keys.

To valid array keys directly with the validate method in a Laravel controller, here's what you'd do:

$request->validate([
    'notifications' => ['array'],
    'keys.*' => ['exists:notifications,id']
], [], [
    'keys' => array_keys($request->notifications)
]);

As a reminder, notifications is the example array structure we saw above.

So, what's going on here?

  1. The first argument contains the standard validation rules
  2. The second argument holds any custom error messages
  3. The third argument allows us to set custom attributes

So, we set keys as the array keys from the data we're sending, using the native array_keys function. This allows us to validate this data within the first argument.

'keys.*' => ['exists:notifications,id']

Using keys.* means validate every item of this array with the rules provided. So, we're checking that each array item's key exists in the database.

Of course, tweak this from here and use your data to validate however needed!

We need to structure things slightly differently to validate array keys within a Laravel form request.

Here's the exact same validation functionality as above (in a controller), but within a form request:

class NotificationUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'notifications' => ['array'],
            'notifications.*.*' => ['exists:notification_channels,type'],
            'keys.*' => ['exists:notifications,id']
        ];
    }

    public function prepareForValidation()
    {
        $this->merge([
            'keys' => array_keys($this->notifications ?? [])
        ]);
    }
}

The only difference here is rather than providing keys as the third argument to the validate method within a controller, we merge it once prepareForValidation gets invoked.

Once prepareForValidation has merged those keys, they'll be validated as usual.

While validating array keys isn't something you'll do frequently, I hope this has helped you if you do need to.

Happy validating!

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Table of contents

Tagged under