How To

What is Localization in Laravel and How to Use it?

In this tutorial, we will learn by example what localization is in Laravel. We will learn Laravel Localization with an example in this guide.

Displaying a webpage or app in the user’s local language helps to target audiences from different regions and cultures across the globe. In Laravel, you can implement language translation through Laravel Localization. Laravel localization allows us to translate an app or site into multiple languages.

Let’s get more idea about Laravel localization in detail with example.

Steps to Implement Localization in Laravel:

Step 1: First, create a locale file in the resources/lang directory of the Laravel project. You must create files according to the number of languages you are using. Here we are creating two files in the resources/lang directory for English and French language with the content below.

resources/lang/en.json 

{
    "Magecomp": "Magecomp",
    "Hey! :Name, Welcome to magecomp": "Hey! :Name, Welcome to Magecomp",
    "To Provide Top Notch E-commerce Products & Services that Build Long-Term Trustworthy Relationships.": "To Provide Top Notch E-commerce Products & Services that Build Long-Term Trustworthy Relationships.",
    "To Be an Organization that Inspires and Fulfills Ecommerce Dreams.": "To Be an Organization that Inspires and Fulfills Ecommerce Dreams."
}

resources/lang/fr.json

{
    "Magecomp": "Magecomp",
    "Hey! :Name, Welcome to magecomp": "Hé! :Name, Bienvenue à Magecomp",
    "To Provide Top Notch E-commerce Products & Services that Build Long-Term Trustworthy Relationships.": "Fournir des produits et services de commerce électronique de premier ordre qui établissent des relations de confiance à long terme.",
    "To Be an Organization that Inspires and Fulfills Ecommerce Dreams.": "Être une organisation qui inspire et réalise les rêves de commerce électronique."
}

Step 2: Now, create a route in the route/web.php file for changing/switching language for the app. We store selected language in session.

route/web.php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;

Route::get('/locale/{locale}', function (Request $request, $locale) {
    Session::put('locale', $locale);
    return redirect()->back();
})->name('locale');

Step 3: Now, you need to create one middleware to set the app/site locale language. In Laravel, php artisan make:middleware {name} command is used to create middleware.

Run the following command at the root of your project

$php artisan make:middleware LocaLocalization

Step 4: See the app/Http/Middleware/LocaLocalization.php file and add the following code to set the app locale language. We are getting the current locale from the session that we store in above.

Your app/Http/Middleware/LocaLocalization.php looks like this.

<?php

namespace App\Http\Middleware;

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

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

Step 5: Add that middleware into your app/Http/Kernel.php to web middleware allies.

/**
     * 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\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\LocaLocalization::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

Step 6: Lastly, create one view file and route for it to see the final output.

resources/views/locale.blade.php

<!DOCTYPE html>
<html>

<head>
    <title>Locale Blog</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <div class="mb-5"></div>
        <div class="card">
            <div class="card-header">
                {{ __('Magecomp') }}
            </div>
            <div class="card-body">
                <h5 class="card-title">{{ __('Hey! :Name, Welcome to magecomp', ["name" => "Johe Doe"]) }}</h5>
                <p class="card-text">{{ __('To Be an Organization that Inspires and Fulfills Ecommerce Dreams.') }}</p>
                <p class="card-text">{{ __('To Provide Top Notch E-commerce Products & Services that Build Long-Term Trustworthy Relationships.') }}</p>
                <div class="btn-group" role="group" aria-label="Basic example">
                    <a href="{{ route('locale', ['locale' => 'en']) }}" type="button" class="btn btn-primary {{ Session::get('locale') == 'en' ? 'active' : ''}}">English</a>
                    <a href="{{ route('locale', ['locale' => 'fr']) }}" type="button" class="btn btn-primary {{ Session::get('locale') == 'fr' ? 'active' : ''}}">French</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
routes/web.php
 Route::get('/', function (Request $request) {
    return view('locale');
});

Output:

Now see the beautiful magic at http://127.0.0.1:8000/ 

English

 

French

Conclusion:

This way, you can implement localization in Laravel. To customize your Laravel project, Hire a Dedicated Laravel Developer. If you have any doubts, let me know through the comment box. Share the article with your friends and stay in touch with us.

Happy Coding!

Click to rate this post!
[Total: 4 Average: 5]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

View Comments

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

5 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago