Benjamin Crozat

Written by Benjamin Crozat on .

How to easily make your Laravel app multilingual - Part 1

Making your app multilingual with Laravel could be extremely easy if route prefixes were documented a little better. That said, every problem has its solution, and here’s the code I use in its most basic form.

It all starts in the routes files. We want to change the language based on the URL. For instance, requesting hello-world.test/fr should display texts in French. Laravel’s routing system has a way to prefix URLs and lets us make use of it.

Let’s create a new Laravel app:

laravel new hello-world

Then, edit the file below:

// routes/web.php

use Illuminate\Support\Facades\Route;

Route::prefix('{language}')
    ->where(['language' => 'en|fr'])
    ->group(function () {
        Route::get('/', function (string $language) {
            app()->setLocale($language);

            return view('welcome');
        });
    });

That’s it. That’s all it takes for a basic implementation of a multilingual Laravel app. We encapsulate all our routes in a group that requires a language prefix (and make sure it can only be equal to “en” or “fr”), then we set the app’s locale to its value.

Below, you can see how to make your texts localizable and how to translate them.

{{-- resources/views/welcome.blade.php --}}

@lang('Hello, World!')

Next, in resources/lang/fr.json:

{
    "Hello, World!": "Bonjour tout le monde !"
}

Also, from now on, you’ll have to specify the language every time you’ll use the URL generator:

<a href="{{ url('/', app()->getLocale()) }}">
    @lang('Hello, World!')
</a>

In the next post, we’ll see how to:

  • Redirect hello-world.test to hello-world.test/en or hello-world.test/fr, depending on the browser’s language;
  • Automatically setting the locale at each request.

Part 2 is available!