Validate Each Array Item with Different Rules Using Rule::forEach()
Validate Each Array Item with Different Rules Using Rule::forEach()
When validating nested arrays, sometimes every item needs its own validation logic.
For example, an API might receive:
[
'companies' => [
['id' => 10],
['id' => 20],
['id' => 30],
],
]
You may need to validate every company ID while also applying additional rules based on that specific company.
Instead of keeping all the logic inside the controller, Laravel provides Rule::forEach().
Basic Usage
use Illuminate\Validation\Rule;
$request->validate([
'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) {
return [
Rule::exists(Company::class, 'id'),
];
}),
]);
The closure runs for each array item and receives:
$value— the current item's value.$attribute— the fully expanded attribute name.
Add Dynamic Rules
The real benefit comes when the rules depend on the current value.
'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) {
return [
Rule::exists(Company::class, 'id'),
new HasPermission('manage-company', $value),
];
}),
Now each company ID can be checked with its own permission logic.