How To Create Multilingual Website using Laravel Localization

How To Create Multilingual Website using Laravel Localization

In this post, I will show you how we can create a multilingual website using Laravel Localization. There are different ways of using localization in Laravel. You can make a Middleware to handle the localization based on user’s selected language or you can use localization based on the specific route. Our final application will look like below.

Laravel Localization App
Laravel Localization App

In this post, we will create a middleware to check if the locale is set then change the locale of the application. I will be showing you a functional example of localization by implementing support for English, French, German, Spanish, Hindi and Urdu languages, so let’s get started.

Laravel Localization Methods

Before jumping to creating an application, let me clarify that there are two types of Localization methods offered by Laravel. You can use the below method to implement localization in your application.

  1. Short Keys
  2. Translation Strings As Keys

Short Keys are stored in resources/lang folder in the form of an array of keyed strings. Translation Strings as Keys are stored in the resources/lang folder in the form of a json file with key value pairs.

Information

I will be using both methods to show you how we can use them.

Creating Laravel Localization Website

The first step, we will create a fresh Laravel project using composer, so type below in your terminal and hit enter.

composer create-project laravel/laravel LocalizationApp

When you have your project ready, go to config/app.php file and check this section.

    /*
    |--------------------------------------------------------------------------
    | 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',

By default, Laravel application locale is set to en means english.

Now if you check resources/lang folder you will find a en folder. All english related translation are stored in here.

Warning

Values stored in files under language specific folder are only accessable as Short Keys because they are stored in the form of an array. For Translation Strings As Keys, we have to store a json file in lang folder with locale specific names.

Step 1. Creating Translation Files

Now we will create, six folders inside resources/lang folder with the locale name. Like below.

    resources
        - lang
            - en
            - es
            - fr
            - ge
            - in
            - pk

Now create a app.php file in all above folders and place the below code respectively.

For en/app.php
return [
    'title' =>  'Localization Exmaple'
];
For es/app.php
return [
    'title' =>  'Ejemplo de localización'
];
For fr/app.php
return [
    'title' =>  'Exemple de localisation'
];
For ge/app.php
return [
    'title' =>  'Lokalisierungsbeispiel'
];
For in/app.php
return [
    'title' =>  'स्थानीयकरण उदाहरण'
];
For pk/app.php
return [
    'title' =>  'لوکلائزیشن مثال''
];

Now we will create below files in resources/lang folder.

    resources
        - lang
            - es.json
            - fr.json
            - ge.json
            - in.json
            - pk.json

After creating the above files, place below code inside each file.

For es/app.php
{
  "Hi there!" : "Hola!",
  "How are you doing?" : "Como estas?",
  "This is basic example of how you use Laravel Localizations" : "Este es un ejemplo básico de cómo usar Localizaciones de Laravel"
}
For fr/app.php
{
  "Hi there!" : "Salut!",
  "How are you doing?" : "Comment allez vous?",
  "This is basic example of how you use Laravel Localizations" : "Ceci est un exemple élémentaire de votre utilisation des localisations Laravel"
}
For ge/app.php
{
  "Hi there!" : "Hallo!",
  "How are you doing?" : "Wie geht es dir?",
  "This is basic example of how you use Laravel Localizations" : "Dies ist ein grundlegendes Beispiel für die Verwendung von Laravel-Lokalisierungen"
}
For in/app.php
{
  "Hi there!" : "नमस्ते!",
  "How are you doing?" : "आप कैसे हैं?",
  "This is basic example of how you use Laravel Localizations" : "यह मूल उदाहरण है कि आप लारवेल लोकलाइज़ेशन का उपयोग कैसे करते हैं"
}
For pk/app.php
{
  "Hi there!" : "ہیلو",
  "How are you doing?" : "آپ کیسے ہیں؟",
  "This is basic example of how you use Laravel Localizations" : "یہ آپ کو لیوریفیل لوکلائزیشن کو کیسے استعمال کرتے ہیں اس کا بنیادی مثال ہے"
}

Note

We are not creating a en.json file, we will be placing that values directly into our view as Laravel load en locale by default.

Now we have placed all translations in place, let’s start working on views and make our application load above translations.

Tip

For each of the language JSON files above, copy the text you want to translate and paste into Google Translate to get its equivalent of the desired language.

Step 2. Setting up Langauges Dropdown Menu

For views templates, run php artisan make:auth and Laravel will scaffold the basic app views which comes out of the box with Laravel installation. For the sake of this application, I have removed the auth routes from routes file and authentication routes from views to load just a basic layout.

Now open your app.blade.php file and place below code which is a markup just for a languages dropdown.

Now rplace home.blade.php file content with below.

If you have noticed in the above code example, we have used trans(), @lang and __() methods to retrieve the translation of the give text. Laravel take text from theses methods and find the translation based on the current locale in above translation files we created.

With above markup, your main application should look something like below:

Laravel Localization App View

Step 3. Setting up Controller and Middleware

First thing first, we will create a route for lang/{locale} which we have just added in our languages dropdown. Add the below route in your web.php routes file and save it.

Route::get('lang/{locale}', '[email protected]');

Next up, we will create a controller to control our language change and middleware for dynamically changing the application’s language. Run below commands in terminal to create a controller and middleware.

php artisan make:controller LocalizationController
php artisan make:middleware Localization

Now edit your localization controller and add index() method as below.

namespace App\Http\Controllers;

use App;
use Illuminate\Http\Request;

class LocalizationController extends Controller
{
    public function index($locale)
    {
        App::setLocale($locale);
        //storing the locale in session to get it back in the middleware
        session()->put('locale', $locale);
        return redirect()->back();
    }
}

In the above code snippet, we are setting the locale which will be passed throughout route using App facade. After setting the locale we are storing the locale in session which will be available to our Middleware and redirecting back.

Now open your newly created middleware App\Http\Middleware\Localization and update the handle method with below code.

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

In our middleware, we are checking if a session value exists with name locale if so we are setting the locale of our application whatever is in that session.

Step 4. Registering Localization Middleware

Now add the middleware in App/Http/Kernel‘s $middlewareGroups array like so:

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

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

Step 5. Showing Current Locale in Dropdown

Now one thing is still missing if we change the language, dropdown still shows Language instead of the current locale. We can fix by adding a switch statement and check what locale we have and based on that we will show the current locale with a flag icon like below.

That’s it. If you have followed the steps along with me, you should have a fully functional application by now as shown above.

Source Code

I have pushed the whole application on github repository, you can grab a copy and play with it.

We have successfully implemented Laravel Localization in this post, feel free to share your opinion in the comments box below.

6 comments on “How To Create Multilingual Website using Laravel Localization

Leave a Reply

Your email address will not be published. Required fields are marked *

*When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Laravel Mail Viewer Package
Laravel Mail Viewer is a package by Harish Toshniwal which enables you to view all the mailable in your Laravel...