Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

it-is-all-about-laravel's avatar

Rename messagebag keys on array element validations

Im validating array elements on a request and have a requirement to group all array element errors under a common key, rather than the default behaviour of error keys that vary for each element. Eg.

// Post request submits
// {'selected_locations' : ['paris', 'paris']}

// Validator rules applied
$rules = [
    'selected_locations'   => 'array',
    'selected_locations.*' => 'distinct'
  ];

// Default behaviour generates error keys of the form 
// selected_locations.0
// selected_locations.1 
// Etc

// Whereas I would like all the errors to be under the same parent key
// selected_locations

What are your recommendations on how best to do this?

0 likes
1 reply

Please or to participate in this conversation.