120+ Engineers
20+ Countries
850+ Projects
750+ Satisfied Clients
4.9 Clutch
120+ Engineers
20+ Countries
850+ Projects
750+ Satisfied Clients
4.9 Clutch
120+ Engineers
20+ Countries
850+ Projects
750+ Satisfied Clients

Laravel Localization Guide: How to Implement Multi-Language Support

  • Set up localization in Laravel for multi-language support

  • Create and manage translation files for different languages

  • Configure routes and middleware to switch languages easily

Last Update: 30 Nov 2024

Laravel Localization Guide: How to Implement Multi-Language Support image

Localization is a powerful feature in Laravel that allows you to create multilingual applications effortlessly. With Laravel 11, this process has become even more streamlined, enabling developers to deliver user-friendly, localized experiences with minimal effort. Whether you’re building an e-commerce platform, a blog, or a corporate website, offering content in multiple languages can significantly enhance accessibility and user engagement.

In this guide, we’ll walk you through the essentials of implementing localization in Laravel 11. From setting up language files to dynamically switching locales, this tutorial will help you create a seamless, multilingual environment for your application. Let’s dive in and make your Laravel app speak multiple languages!

Publishing the Language Files

The default Laravel application does not come with a lang directory. To customize Laravel’s language files or add your own, you can generate the lang directory using the lang:publish Artisan command. This command will create the lang directory in your project and add Laravel’s default language files. Simply run:

php artisan lang:publish

It will give add a lang folder in your default laravel folder structure of your project like the image.

content image

Configuring the Locale

The default language for your application is defined in the locale option of the config/app.php configuration file. This is usually set using the APP_LOCALE environment variable. You can change this value to match the language needs of your application.

Additionally, you can set a "fallback language" that Laravel will use if a translation string is missing in the default language. This fallback language is also configured in the config/app.php file and is typically set through the APP_FALLBACK_LOCALE environment variable.

For now, what we’ll change in config/app.php is like below - 

content image

Getting a Middleware

We’ll create a Localization Middleware to globally handle the language task. At first, run -

php artisan make:middleware Localization

It will create a middleware, which will be available in App\Http\Middleware\Localization.php . If you want auto language select feature based on the location or country or region, you will need to retrieve the user location via their IP or location. For now, we’ll be using the IP based method. We have to run the following commands to install a package -

composer require stevebauman/location
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"

Then we’ll code our middleware like this -

content image

Including the middleware in Configuration

Now, we have to include this middleware in app configuration so that by default it will be included everywhere. For this, we have to modify the bootstrap/app.php file like below - 

content image

Contents of JSON files and Structure

The files here will include only a json object like the image -

So what’s the key and value here? The keys are defined words in our blade files like following -

And the values are what will be replaced depending on the language. That means, “about” will be replaced with “About” in the final result for English. For Espanol, it will be "Acerca de" and so as the selected language.

Blade Contents to choose Language

We’ll be needed to include extra css and js library in the header in order to get a language selector like the following images - 

 

For now, I will provide code example to get only the flags system. But the css and js library will remain same for whatever type of selector you want to show. We’ll need to add some js to get this selector workable and a route that will help us to refresh the page after setting up the language.

  • CSS Library 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta3/css/bootstrap-select.min.css" integrity="sha512-g2SduJKxa4Lbn3GW+Q7rNz+pKP9AWMR++Ta8fgwsZRCUsawjPvF/BxSMkGS61VsR9yinGoEgrHPGPn2mrj8+4w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/css/flag-icon.min.css" integrity="sha512-Kr0zV71OG2KVTHFnCHHccI+3melPJbu/xPhJOK983MVj/1aigFkqktSzJahWSTkJllaLeSGJQY57xW9E3ndmDw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  • JS Library 
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta3/js/bootstrap-select.min.js" integrity="sha512-yrOmjPdp8qH8hgLfWpSFhC/+R9Cj9USL8uJxYIveJZGAiedxyIxwNw4RsLDlcjNlIRR4kkHaDHSmNHAkxFTmgg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  • Custom JS
            $(function() {
                $('.selectpicker').selectpicker();
            });
    
            $('#langSelect').on('change', function() {
                var lang = $(this).val();
    
                $.ajax({
                    url: '/set-locale',
                    method: 'POST',
                    data: {
                        locale: lang,
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function() {
                        window.location.reload();
                    },
                    error: function() {
                        alert('Failed to change language. Please try again.');
                    }
                });
            });
  • Route
    Route::post('/set-locale', function (Illuminate\Http\Request $request) {
        $locale = $request->input('locale');
        if (in_array($locale, ['en', 'es', 'pl', 'pt', 'ru', 'fr'])) {
            session(['locale' => $locale]);
            app()->setLocale($locale);
            return response()->json(['success' => true]);
        }
        return response()->json(['success' => false], 400);
    })->name('set-locale');
    
  • Blade
    <select id="langSelect" class="selectpicker" data-width="fit">
                        <option value="en" {{ app()->getLocale() == 'en' ? 'selected' : '' }} data-content='<span class="flag-icon flag-icon-us"></span>'></option>
                        <option value="es" {{ app()->getLocale() == 'es' ? 'selected' : '' }} data-content='<span class="flag-icon flag-icon-es"></span>'></option>
                        <option value="pl" {{ app()->getLocale() == 'pl' ? 'selected' : '' }} data-content='<span class="flag-icon flag-icon-pl"></span>'></option>
                        <option value="pt" {{ app()->getLocale() == 'pt' ? 'selected' : '' }} data-content='<span class="flag-icon flag-icon-pt"></span>'></option>
                        <option value="ru" {{ app()->getLocale() == 'ru' ? 'selected' : '' }} data-content='<span class="flag-icon flag-icon-ru"></span>'></option>
                        <option value="fr" {{ app()->getLocale() == 'fr' ? 'selected' : '' }} data-content='<span class="flag-icon flag-icon-fr"></span>'></option>
    </select>
    

Conclusion

Implementing localization in Laravel 11 is a straightforward yet powerful way to make your application accessible to a global audience. By leveraging Laravel's built-in localization features, you can easily manage language files, switch between locales dynamically, and provide fallback options for missing translations.

With just a few steps—setting up your lang directory, defining your default and fallback languages, and adding translations—you can transform your application into a multilingual platform. As the demand for personalized and localized content grows, this feature becomes a critical tool for developers aiming to deliver user-centric experiences.

Start integrating localization into your Laravel application today and take a significant step towards building truly inclusive digital experiences!

Frequently Asked Questions

Trendingblogs
Get the best of our content straight to your inbox!

By submitting, you agree to our privacy policy.

Have a Project To Discuss?

We're ready!

Let's
Talk