Reputation: 1014
I know how to set default language in application by using App::setLocale('es');
I'm thinking about setting individual language per user after an user logs in.
Currently, the only way I have in mind is to set a general language and use variable inside a Lang::get() command:
$user_language = 'gr';
Lang::get('messages.welcome'.$user_language);
Is there any other way of setting language setting per user?
Upvotes: 1
Views: 6527
Reputation: 99
If you want to set locale per each user is not recommended to use App::setLocale($lang) because it changes the global settings in the app so the best solution is to use
Lang::get($key, $replace, $locale).
We can use different files per each language. Having this key on
en
'required' => 'Field is required'
es
'required' => 'Campo es requerido'
And this structure of files
resources
lang
en
messages.php
es
messages.php
To recover the correct key you should call
$user_language = 'en';
Lang::get('messages.required',[], $user_language)
Upvotes: 0
Reputation: 44526
Why not just use App::setLocale()
to set the language according to the user preferences if the user is logged in. According to the Laravel Docs:
You may change the active language at any time using the
App::setLocale
method.
So you could do that maybe like this:
App::before(function($request)
{
// If user is logged in
if (Auth::check())
{
// Get the user specific language
$lang = Auth::user()->language;
// Set the language
App::setLocale($lang);
}
});
Upvotes: 11