Q
What is the best way to setup a multi language website with Laravel? The URL must contain the language (nl, fr, en). For example: mywebsite.com/en/faq. Most examples and tutorials I find use the session to store the current language which is completely useless of course. I should be able to directly link to a page in a specific language.
I could create a route per language but that does not really seem like a good idea. Ideally this could be made dynamic in order to easily create more locales.
Answers
I'm curious, why you cannot use session (it's a true question, I really would like to understand)?
You can use the same approach than with session: create a middleware to set App::setLocale("YourLanguage") based on query string.
public function handle(Request $request, Closure $next)
{
// This example try to get "language" variable, \
// if it not exist will define pt as default \
// you also can use some config value: replace 'pt' by Config::get('app.locale')
App::setLocale(request('language', 'pt'));
return $next($request);
}
Or you can do it by Route:
// This example check the if the language exist in an array before apply
Route::get('/{language?}', function ($language = null) {
if (isset($language) && in_array($language, config('app.available_locales'))) {
app()->setLocale($language);
} else {
app()->setLocale(Config::get('app.locale'));
}
return view('welcome');
});
Source:
Laravel change language depending on a $_GET parameter
https://lokalise.com/blog/laravel-localization-step-by-step/
0 comments:
Post a Comment
Thanks