laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Laravel custom attribute translation for array validation #2533

Open vpratfr opened 3 years ago

vpratfr commented 3 years ago

Description:

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() => $this->someComputation($itemData['height'], $itemData['length'])
   );
}

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 ».

driesvints commented 3 years ago

Heya, thanks for submitting this.

This seems like a feature request or an improvement so I'm moving this to the ideas repository instead. It's best to post these in the ideas repository in the future to get support for your idea. After that you may send a PR to the framework. Please only use the laravel/framework issue tracker to report bugs and issues with the framework.

Thanks!

vpratfr commented 3 years ago

Seems also somehow related to that one, where someone was open to submit a PR but did not get any feedback from you.

https://github.com/laravel/ideas/issues/1771

driesvints commented 3 years ago

@vpratfr we don't really monitor issues in this repo. This repo is meant as a discussion place for community members. If you want to propose something it's better to send in a PR so we can look at actual code.

vpratfr commented 3 years ago

ok. Here you go: https://github.com/laravel/framework/pull/36587