Benjamin Crozat

Written by Benjamin Crozat on .

How to easily make your Laravel app multilingual - Part 2

Part 1 of this series is available here.

Our internationalization system is pretty basic right now. We have more requirements to meet. Let’s dive in!

Redirect hello-world.test to the appropriate language

It’s pretty simple there. Let’s edit our routes/web.php and create a route for /.

In the code below, you’ll notice that I’m asking Laravel to use a 301 HTTP code instead of 302 (which is the default value). It’ll help prevent search engines from indexing the same page with different URLs.

Route::get('/', function () { // For each language we support. foreach (['en', 'fr'] as $locale) { // We check if it matches the browser’s preferred language. if (str_contains($request->getPreferredLanguage(), $locale)) { // If it does, we redirect to it. return redirect()->route('home', $locale, 301); } } // If it doesn’t, we fall back on the default language. return redirect()->route('home', $request->getLocale(), 301); });

Automatically setting the locale at each request

Until now, we had to use app()->setLocale() in each of our routes to display texts in the desired language. Instead, let’s create a middleware that’ll do it automatically.

php artisan make:middleware SetLocale public function handle(Request $request, Closure $next) { // Set the locale… app()->setLocale( // … with the desired language (e.g. https://hello-world.test/fr/foo/bar). $request->route()->parameter('language') ); return $next($request); }

How to improve what we’ve done?

  • You could extract our new route to a RootController, just to clean up the mess in web.php;
  • Write tests!

I’ll probably write a third part, covering the required testing to make sure our code works as expected.

Until next time!