Reputation: 6564
Trying to see how it is possible to replace a translation string programmatically in a controlled situation.
e.g. the default i18n has
[
"button": "xxx"
]
So when we run trans('button')
we get back xxx
However we're in a situation with a 3rd party package where we need to change this result in a special circumstance, e.g imagine...
if (request()->mode === 'create') {
app('translator')->overwrite('button', 'yyyy');
}
So when we do trans('button')
we get our new yyyy
We're not expecting this to persist across pages or anything like that, just a one-off, on the fly change before we get to the view much as you can do config(['key' => 'new value'])
;
Currently, we have a solution that feels a bit delicate and hacky, that we do not think will work with config caching e.g, so ideally would like a proper solution.
return [
'button' => request()->is('custom-page') ? 'custom text' : 'default text',
];
Upvotes: 0
Views: 679
Reputation: 6799
You can overwrite the translation string using the following code:
app('translator')->addLines(['form.button' => 'yyyyy'] , 'en');
In your case :
if (request()->mode === 'create')
{
app('translator')->addLines(['form.button' => 'yyyyy'] , 'en');
}
Please note that form
in form.button
is the name of the language file, so you might need to change it based on your file name.
Edited
If you have a namespace then pass the name as third parameter like following:
app('translator')->addLines(['form.button' => 'yyyyy'] , 'en', 'your_name_space');
Upvotes: 2