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: 3 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

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

19 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

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

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

7 days ago