0
votes

I'm using Laravel's HTTP Request Class to validate some form data. For some fields I needed a closure to make a custom validation.

Since my application has two localizations (english and german) I need to translate the error messages if the validation fails, which I already did.

The only problem I had was with the $fail()-message in the closure.

This is how I translate the message depending on the current localization within the closure:

if (app()->getLocale() == 'en') {
   $fail('Please choose a name for "' .$value. '" in order to continue.');
} 
elseif (app()->getLocale() == 'de') {
   $fail('Bitte wählen Sie einen Namen für "' .$value. '" um fortzufahren.');
}

I know I can use the en.json-file which I'm using for the translation of the whole site, but I wouldn't be able to use the $valueinside of the sentence.

I'm wondering if there is a better way to accomplish this?

EDIT

Since I'm using a closure I have to write the 'default' german error message inside the closure like this:

$fail('Bitte wählen Sie einen Namen für "' .$value. '" um fortzufahren.');

Doing it like this I get the value of the $value inside the error message that gets displayed in the view like this:

@if ($errors->has('person.*.name'))
   <label class="error-small">@lang($errors->first('person.*.name'))</label>
@endif

So the $value variable will be inserted in the message, so I can't access the variable anymore through the json translation file..

1

1 Answers

1
votes

And why can't you pass a parameter?

Take a look at the documentation.

Something like this:

messages.php

'chose_name' => 'Please choose a name for :name in order to continue.'
__('messages.chose_name', ['name' => $value])

-- EDIT

For JSON

__('Please choose a name for :name in order to continue.', ['name' => $value])

Have you tried this:

de.json

{"Please choose a name for :name in order to continue.": "Bitte wählen Sie einen Namen für :name um fortzufahren."}