In a complex form, we need to build some validation rules for an array which should get triggered only on some complex logic based on each item data.
The way array validation is defined is usually something like that
$validator->sometimes(
"items.*.level",
'required|int|min:0',
fn($formData) => /* $formData is the whole form data, not for the current item */
);
However, as seen above, the closure to determine when to trigger those rules is global to the form data, not to the item's data.
Hence we dynamically add rules for each item in the form like that:
foreach ($formData as $itemId => $itemData) {
$validator->sometimes(
"items.$itemId.level",
'required|int|min:0',
fn() => $itemData['type'] === 123 && $itemData['category'] > 30
);
}
We have to do that because there is no way I know of to define a sometimes rule which will look into the corresponding item's data only.
All that works nicely. One issue we have is with the translation for the validation messages. We have in the validation.php file:
'attributes' => [
'items.*.level' => 'Niveau',
]
That does not get picked up. The message shown is still « The field items.12.level is required » instead of « The field Niveau is required » .
Is there any way to have the validator pick the closest matching attribute name and get that * placeholder behave as it should?