Step-by-Step Laravel Localization [Guide]

Step-by-Step Laravel Localization [Guide]
Table of Contents

Laravel localization is a powerful that enables developers to create multilingual websites. By implementing web localization in your Laravel projects, you can provide a personalized user experience for visitors from different linguistic backgrounds, ultimately expanding your reach and improving user engagement.

We’ll walk you through implementing localization in your Laravel application and introduce you to a tool that can simplify and enhance your localization efforts!

Why should you localize the Laravel website?

Step-by-Step Laravel Localization [Guide]

Here are some important reasons why you should localize your Laravel website.

  • Reach a global audience: By localizing your Laravel website, you can extend the reach of your app to an international audience. This allows users from different countries and language backgrounds to understand and interact with your content.
  • Improves user experience: Localization allows users to interact with the app in their native language, which significantly improves user experience. This can increase engagement rates, reduce bounce rates, and increase conversions.
  • Competitive advantage: In a competitive global market, offering apps in multiple languages can provide a significant edge over competitors. It shows your commitment to international markets and can help you enter new markets more effectively.
  • Improves SEO: Well-localized websites tend to rank better in search engines for searches in a particular language. This can increase your blog traffic and online visibility in various markets with multilingual translation.

Requirements for a multilingual Laravel localization

Step-by-Step Laravel Localization [Guide]

There are a few requirements and steps to consider when implementing multilingual localization in Laravel.

  • To get the latest localization features, make sure you are using the latest version of Laravel (e.g., version 10.x).
  • A basic understanding of PHP and the Laravel framework will be helpful in the implementation process.
  • Set up a local development environment or server that supports Laravel, including a web server and database.
  • Determine the languages that your application will support from the start.

Simple Laravel translations

Step-by-Step Laravel Localization [Guide]

After understanding what requirements must be met before translating a Laravel application or web, we will provide some steps for translating Laravel simply.

To do this, open the view file that you want to localize, for example, resources/views/welcome.blade.php. Then, replace the body tag with the following code.

				
					<body class="antialiased">
    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 sm:items-center py-4 sm:pt-0">
        <div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
            <div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
                Welcome to Linguise website!
            </div>
        </div>
    </div>
</body>
				
			

As you can see, the text above is currently written directly in the code. This is less efficient and makes it difficult to translate websites to different languages (internationalization). 

We are going to make the above text more flexible so that it can be easily adapted to different languages. Laravel provides a very helpful feature for this; the localization system. As a first step, replace the existing text with the following code.

				
					{{ __('Welcome to Linguise website!') }}
				
			

Laravel will display the above text by default and look up the translation if the user selects a language other than English. In this case, English will be used as the application’s default language.

Setting up locales in a Laravel multilingual web

Step-by-Step Laravel Localization [Guide]

But how does Laravel determine the current language or know which languages are available in the application? It checks the locale settings in the config/app.php file. Open this file and look for the following two keys.

				
					/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/

'fallback_locale' => 'en',

				
			

The explanation above the keys should be clear. In summary, the locale key holds the default locale for your application (if no other locale is specified in the code). The fallback_locale is activated if a non-existent locale is requested in your application.

Now, let’s add a new key to this file to provide a list of all supported locales.

				
					/*
|--------------------------------------------------------------------------
| Available locales
|--------------------------------------------------------------------------
|
| List all locales that your application works with
|
*/

'available_locales' => [
  'English' => 'en',
  'Italian' => 'it',
  'French' => 'fr',
],


				
			

At this point, we have tried Laravel web to support three languages, namely English, Italian, and French.

Laravel translation files overview

Step-by-Step Laravel Localization [Guide]

In Laravel, as in many other frameworks, translations for different languages are stored in separate files. Two methods are used for organizing these translation files.

The older method stores files in the following structure: resources/lang/{en,fr,it}/{myfile.php}. The newer method uses JSON files, such as resources/lang/{fr.json, it.json}. This article will focus on the newer method, though the principles are similar for the older method, aside from differences in how translation keys are named and accessed.

For languages with regional variations, you should name the language directories or files according to the ISO 15897 standard. For instance, British English would be named en_GB instead of en-gb.

General information

In Laravel, as with many frameworks, translations for different languages are stored in separate files. There are two primary methods for organizing Laravel translation files.

  1. The legacy approach involves storing files under the path: resources/lang/{en,fr,it}/{myfile.php}.
  2. The modern approach utilizes resources/lang/{fr.json, it.json} files.

This article will concentrate on the second method, though the principles are applicable to both (with variations in how translation keys are named and accessed).

For languages that vary by region, it’s recommended to name language directories/files according to ISO 15897 standards. For instance, British English would be denoted as en_GB rather than en-gb.

Creating Laravel translation files

Having configured the locales for our application, we can proceed to translate our default welcome message.

Let’s begin by creating new localization files in JSON format within the resources/lang directory. First, we’ll create a resources/lang/it.json file and populate it with the appropriate translations.

				
					{
  "Welcome to Linguise website!": "Benvenuti nel sito web di Linguise!"
}

				
			

Next, add a resources/lang/fr.json file.

				
					{
 "Welcome to Linguise website!": "Bienvenue sur le site de Linguise"
}

				
			

As you can observe, we’re consistently referencing the default message from the welcome.blade.php file ({{ __(‘Welcome to Linguise website!’) }}). There’s no need to create an en.json file, as Laravel automatically recognizes that the default messages are in English.

Setting language switcher in a Laravel multilingual app

Step-by-Step Laravel Localization [Guide]

Furthermore, Laravel is not yet set up to override the local language, so for now, we will handle the translation directly within the route. Modify the default welcome route inside the routes/web.php file like this.

				
					Route::get('/{locale?}', function ($locale = null) {
    if (isset($locale) && in_array($locale, config('app.available_locales'))) {
        app()->setLocale($locale);
    }
    
    return view('welcome');
});
				
			

In this case, we’re capturing an optional locale GET parameter and setting the current locale based on it (if the requested locale is supported).

Now, you can visit your website and include any of the supported languages as the first segment in the URL. For instance, navigating to localhost/it or localhost/fr will display the localized content. If you don’t specify a locale or choose one that isn’t supported, Laravel will default to English (en).

Localization middleware for Laravel

Including the locale in every URL might not be ideal and could disrupt the site’s visual appeal. To address this, we’ll set up a language switcher and utilize the user session to display the translated content. You can create new middleware in the app/Http/Middleware/Localization.php file, or generate it by running the artisan make:middleware Localization command.

Then, add the following code inside.

				
					<?php

namespace App\Http\Middleware;

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

class Localization
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
    public function handle(Request $request, Closure $next)
    {
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }
        return $next($request);
    }
}


				
			

This middleware will direct Laravel to use the location selected by the user if this option is present in the session.

Since we need the operation to run on every request, add it to the default middleware stack in app/Http/Kernel.php for the web middleware group.

				
					/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
  'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \App\Http\Middleware\Localization::class, // <--- add this
],


				
			

Modifying routes

Next, define a route to change the locale in the routes/web.php file. We’re using a closure route here, but you can place the same code inside a controller if you prefer.

				
					Route::get('language/{locale}', function ($locale) {
   app()->setLocale($locale);
   session()->put('locale', $locale);
   return redirect()->back();
});

				
			

Additionally, remove the locale switching that was previously added to the default welcome route. Your root route should now look like this.

				
					Route::get('/', function () {
   return view('welcome');
});

				
			

Once this is done, the user can only switch the active language by visiting localhost/language/{locale}. The selected locale will be saved in the session, and users will be redirected back to their previous page (as handled by the Localization middleware). 

To test it, go to localhost/language/it (assuming the session cookie is active in your browser), and you should see the translated content. You can navigate the site or refresh the page, and the chosen language will remain in effect.

Language switcher implementation

Now, we need to provide the user with a clickable option to change the language switcher Laravel web rather than requiring them to enter locale codes in the URL manually. To achieve this, create a simple language switcher. Add a new file at resources/views/partials/language_switcher.blade.php and insert the following code.

				
					<div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
    @foreach($available_locales as $locale_name => $available_locale)
        @if($available_locale === $current_locale)
            <span class="ml-2 mr-2 text-gray-700">{{ $locale_name }}</span>
        @else
            <a class="ml-1 underline ml-2 mr-2" href="language/{{ $available_locale }}">
                <span>{{ $locale_name }}</span>
            </a>
        @endif
    @endforeach
</div>


				
			

To include the newly created language switcher in the “welcome” view, simply add the following line to your welcome.blade.php file where you’d like the switcher to appear.

				
					<body class="antialiased">
    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 sm:items-center py-4 sm:pt-0">
        <div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
            @include('partials/language_switcher')

            <div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
                {{ __('Welcome to our website!') }}
            </div>
        </div>
    </div>
</body>


				
			

Open the app/Providers/AppServiceProvider.php file and add the following code in the boot() method to share the current locale with all views when the language switcher is used

				
					* Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    view()->composer('partials.language_switcher', function ($view) {
        $view->with('current_locale', app()->getLocale());
        $view->with('available_locales', config('app.available_locales'));
    });
}


				
			

Advanced translation features in Laravel PHP

Step-by-Step Laravel Localization [Guide]

In this discussion, we will then handle other localization components, namely date, number, and currency. Here are the steps.

Localized dates in Laravel

Handling dates and times is crucial in the localization process. Laravel uses Carbon to manage dates and times. Here’s how you can use Carbon to display a localized date.

				
					<?php
Route::get('/', function () {
    $today = \Carbon\Carbon::now()
        ->settings(
            [
                'locale' => app()->getLocale(),
            ]
        );

    // LL is macro placeholder for MMMM D, YYYY (you could write same as dddd, MMMM D, YYYY)
    $dateMessage = $today->isoFormat('dddd, LL');

    return view('welcome', [
        'date_message' => $dateMessage
    ]);
});


				
			

This code sets the Carbon locale based on the application’s current locale and formats the date accordingly.

To display the localized date in a view:

				
					{{ __('Welcome to our website, :Name', ['name' => ‘Johb’]) }}
<br>
{{ trans_choice('{0} There :form :count apples|{1} There :form just :count apple|[2,19] There :form :count apples', 1, ['form' => 'is']) }}
<br>
{{ $date_message }}


				
			

Formatting numbers and currencies

Different countries have various ways of formatting numbers. For instance.

  • France → 123 123,12
  • Germany → 123.123,12
  • Japan → 123,123

To accommodate these variations in your Laravel application, you can use NumberFormatter.

				
					<?php
$num = NumberFormatter::create('en_US', NumberFormatter::DECIMAL);

$num2 = NumberFormatter::create('fr', NumberFormatter::DECIMAL);
				
			

You can also spell out numbers in a specific language.

				
					<?php
$num = NumberFormatter::create('en_US', NumberFormatter::SPELLOUT);

$num2 = NumberFormatter::create('it', NumberFormatter::SPELLOUT);
				
			

Here are the currencies. For the French locale (`fr`), the currency will be displayed in euros (€), while for the US locale (`en_US`), it will be shown in US dollars ($).

				
					<?php
$currency1 = NumberFormatter::create('it', NumberFormatter::CURRENCY);

$currency2 = NumberFormatter::create('en_US', NumberFormatter::CURRENCY);
				
			
Break Language Barriers
Say goodbye to language barriers and hello to limitless growth! Try our automatic translation service today.

Alternative solution Laravel localization with Linguise

Step-by-Step Laravel Localization [Guide]

After understanding the steps of Laravel localization as described in the article, this process involves many steps that require users to understand the Laravel program code in depth.

This can certainly make it difficult for novice users who want to localize their applications. Therefore, a more innovative solution is needed that is capable of fast translation, supports localization, and requires only a few simple steps to implement.

One promising solution is Linguise. Linguise offers an easier and more efficient approach to Laravel localization without the need for in-depth coding knowledge. Key features of Linguise include.

  • Easy integration with Laravel
  • Customize language switcher without coding
  • Image translation
  • Live editor to customize translations to the local context
  • Dynamic translation for dynamically generated content
  • SEO optimization for multi-language versions

The steps to install Linguise on Laravel websites can also be done easily. Here’s a brief explanation.

  1. Create a Linguise account (use the 30-day free trial for free)
  2. Register your Laravel web domain and enter some information. You will get an API key.
  3. Upload and connect the Linguise translation script to the Laravel folder you got.
  4. Setup language URLs in the htaccess file.
  5. Insert the language switcher script in the head of your HTML.
  6. Customize the language switcher as needed
  7. The language switcher will appear on the Laravel web, and the content can be translated automatically.

How? With Linguise, you only need to register and activate, and the language switcher will appear. After that, you are free to localize, for example, through the live editor, translate media, images, etc.

Ready to explore new markets? Try our automatic translation service for free with our 1-month risk-free trial. No credit card needed!

Conclusion

Laravel localization is a powerful feature that enables developers to create multilingual websites and applications. As we’ve seen, the built-in Laravel localization process involves multiple steps and requires a good understanding of the framework. It can be challenging for beginners or those looking for a quicker solution.

Tools like Linguise provide an innovative alternative for those seeking a more streamlined approach. These solutions offer rapid translation capabilities, easy integration, and user-friendly features like customizable language switchers and image translation. Now, create your Linguise account and enjoy our feature for localizing your Laravel!

You may also be interested in reading

Don't miss out!
Subscribe to our Newsletter

Receive news about website automatic translation, international SEO and more!

Invalid email address
Give it a try. One per month and you can unsubscribe at any time.

Don't leave without sharing your email!

We can’t guarantee you’ll win the lottery, but we can promise some interesting informational news around translation and occasional discounts.

Don't miss out!
Invalid email address