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 $value
inside 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..