Creating a Multilingual Laravel Project

In this article, we explore Laravel, one of the most popular PHP frameworks, and its tools for building multilingual web applications. Laravel provides simple, effective localization and translation tools, making it a useful choice for developers who want their projects to reach audiences in multiple languages.

We will cover the concepts and techniques needed to add language support to a Laravel project. From configuring localization to translating interface text and content, you will learn how to manage multilingual resources and keep your project flexible enough to support additional languages later.

Whether you are building a blog, an online store or a complex web application, understanding multilingual development in Laravel is a valuable skill. Let's get started!

How localization works in Laravel

Laravel supports localization, and setting it up for your project is straightforward. Follow these steps:

  1. First, create a resources/lang directory in the project root. Publish the language resources:
    php artisan lang:publish
  2. Inside this directory, create a subdirectory for each supported language. For example, use en for English and ru for Russian.
  3. Create translation files in each language directory. File names should correspond to the translation keys used in your code. For example, to store the English text Hello, world!, create resources/lang/en/messages.php and add: 'hello' => 'Hello, world!'.
  4. Use the trans() function to retrieve translations. For example, to display the English translation of hello, write: {{ trans('messages.hello') }}.
  5. To change the application language, use SetLocaleMiddleware. Create the middleware and add it to the $middleware array in app/Http/Kernel.php. In the middleware, set the language with App::setLocale(). For example:
  6. You can also add a language switcher so visitors can select their preferred language. Create a form with buttons for each language and send a POST request to /lang/{locale}, where {locale} is the language code. In the controller handling that URL, call App::setLocale() with the selected language and redirect the visitor back.

A localization implementation example

A concrete Laravel implementation might look like this:

1. Language switcher

html

<!-- HTML разметка для переключателя языка -->
<ul>
<li><a href="{{ route('lang.switch', ['locale' => 'en']) }}">English</a></li>
<li><a href="{{ route('lang.switch', ['locale' => 'ru']) }}">Русский</a></li>
</ul>

The route() helper generates the URL, with the locale parameter set to the selected language.

2. Route and controller for switching languages

// routes/web.php

Route::get('lang/{locale}', [LanguageController::class, 'switch'])->name('lang.switch');

// app/Http/Controllers/LanguageController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class LanguageController extends Controller
{
  public function switch($locale)
  {
      // Сохраняем выбранный язык в сессии
      Session::put('locale', $locale);

      // Устанавливаем приложение на выбранный язык
      App::setLocale($locale);

      // Редиректим пользователя на домашнюю страницу
      return redirect()->route('home', ['locale'=>$locale]);
}
}

This defines a lang/{locale} route handled by LanguageController's switch() method. The method saves the chosen language in the Laravel session, sets the application locale and redirects the visitor to the previous page.

3. Middleware to determine the current language

// app/Http/Middleware/SetLocale.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$locale = $request->route('locale'); // Получаем значение префикса locale из маршрута

// Получаем список поддерживаемых языков из конфигурации Laravel
$locales = config('app.locales');

if ($locale) {
if (!in_array($locale, $locales)) {
abort(404);
}
App::setLocale($locale); // Устанавливаем локаль равной значению префикса locale
} else {
self::setLocale($request);
}

return $next($request);
}

public function setLocale(Request $request): string
{
// Получаем текущий язык из сессии
$locale = Session::get('locale');
if ($locale) {
App::setLocale($locale);
} else {
$locale = self::setDefaultLocale($request);
}
return $locale;
}

public function setDefaultLocale(Request $request): string
{
// Если пользователь уже выбрал язык, то не меняем его по умолчанию
if (Session::has('locale')) {
return Session::get('locale');
}

// Получаем список поддерживаемых языков из конфигурации Laravel
$locales = config('app.locales');

// Получаем список языков из заголовка Accept-Language в запросе
$browserLocales = $request->getLanguages();

// Ищем первый поддерживаемый язык в списке языков браузера
foreach ($browserLocales as $locale) {
if (in_array($locale, $locales)) {
// Если найден поддерживаемый язык, устанавливаем его как локаль приложения и сохраняем в сессии
App::setLocale($locale);
Session::put('locale', $locale);
return $locale;
}
}

// Если ни один из языков браузера не поддерживается приложением, устанавливаем английский язык по умолчанию
$locale = 'en';
App::setLocale($locale);
Session::put('locale', $locale);
return $locale;
}
}

The SetLocale middleware runs before each request and sets the application locale from the session. This displays content in the selected language across the website.

Also add this line to the //app/config.php configuration file: 

'locales' => ['ru', 'en'],

Remember to add the middleware to the web group in //app/Http/kernel.php:

\App\Http\Middleware\SetLocale::class,

4. Language files

Laravel language files let you translate text into different languages. Create .json files in the /lang directory, for example:

//lang/en.json

{
"welcome": "Welcome to my website!"  
}

//lang/ru.json

{
"welcome": "Добро пожаловать на мой сайт!"  
}

Here we define keys and values for each language. The example translates Welcome to my website! into English and Russian.

5. Using language files in code

Retrieve translations in your controllers with trans() or its shorthand, __().

These are the main steps required to add localization to Laravel.