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?
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!