2

I need a request validation rule to return a custom message upon failure, and since the field being validating is an array with a min:x rule i'd like to have a custom message for both singular and plural variations.

I'm just wondering how to pass to the trans_choice() function the :min parameter from the validation rule:

Translation file:

'array' => [
    'field' => [
        'min' => 'You need to select at least one item.|you need to select at least :min items',
    ],
],

Request message() method:

public function messages() {
    'my.array.field.min' => trans_choice('translations::array.field.min', ???),
}
fudo
  • 2,254
  • 4
  • 22
  • 44

1 Answers1

0

It seems like there's nothing built into Laravel to use trans_choice whenever you can pluralise a translation string.

A way you could solve that is by temporarily (or permanently, whatever fits your use-case) changing the replacer for the min rule to something like this:

Validator::replacer('min', function ($message, $attribute, $rule, $parameters, $validator) {  
    $minValue = $parameters[0];

    $message = Str::contains($message, '|')
        ? trans_choice($message, $minValue)
        : $message;
  
    return str_replace(':min', $minValue, $message);
});

Or by extending the Validator factory to work in your favour, but since that requires you to change many of it's methods I don't really recommend that.

Dan
  • 5,140
  • 2
  • 15
  • 30