After googling and looking for a good way to implement a language switcher to my new Laravel Application that i was working on, i have developed a solution that was best for what i was going for: a seamless integration, easy to use.
First, you have to set up atleast two language files. You can find out how and where to set these up in laravel’s localization documentation. After setting your language files up, you must find a way to store the current selected language in the environment. I have chosen the session for this, however you can get crazy with it and use cookies, or whatever you need!
To set it up on every request, you have to create a service provider. I have named mine “LocaleServiceProvider”. Its purpose is only to set the new app locale to the one in the config as a default fallback. You can create this file anywhere you want. Usually in your app folder, you may create a folder named Providers… up to you.
//app/Providers/LocaleServiceProvicer.php
namespace app\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\App;
class LocaleServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$language = Session::get('language', Config::get('app.locale'));
App::setLocale($language);
}
}
To enable the new functionality, you have to include the newly created service provider to config/app.php. Open the file up, and look for the ‘providers’ array
'providers' => [
//at the bottom of the array, just include your provider.
app\Providers\RouteServiceProvider::class,
]
However, we need to set that session flag that holds the user selected language. How do we do that? I have a small dropdown in my view that links to locale/LANGUAGE, language being en for english, dk for danish, etc. I handled that in the routes folder, but feel free to create a controller function if you want.
Route::get('locale/{locale}', function ($locale)
{
Session::set('language', $locale);
return redirect('/');
});
Now, you can start using your new phrases, translated in your views:
<a href="{{ url('login') }}">{{ trans('menu.login') }} / {{ trans('menu.signup') }} <i class="fa fa-lock after"></i></a>
I am considering creating this code as a package that you can pull from github or packagist, if anyone is interested!
The package is has been created, it will be described properly in the Open Source section. You can check it out on github or packagist.
Posted July 8, 2016 9:28 am