DEV Community

Al Shahriar
Al Shahriar

Posted on

A Step To Step Guide For Laravel Localization

Hello and welcome to this tutorial on Laravel localization! In this tutorial, we'll be going over how to implement localization in your Laravel project.

Localization is the process of adapting your application to a specific locale or language. This is an important feature to include in your application if you want to reach a wider audience.

Step 1: Install Laravel

composer create-project laravel/laravel:^9.0 localization

Enter fullscreen mode Exit fullscreen mode

Step 2: Create Controller
php artisan make:controller LocalizationController --invokable


public function __invoke($langVal)
    {
       Session::put("locale",$langVal);
       return response()->json(['success'=>'Language change 
       successfully.']);

    }
Enter fullscreen mode Exit fullscreen mode

Step 3: Make a route in web.php

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

Route::get('lang/{langVal}', LocalizationController::class);
Enter fullscreen mode Exit fullscreen mode

Step 4: Make a MiddleWare

php artisan make:middleware Localization

public function handle(Request $request, Closure $next)
    {
        if(Session::has("locale"))
            App::setLocale(Session::get("locale"));
        else
            App::setLocale(config("app.locale"));

        return $next($request);
    }
Enter fullscreen mode Exit fullscreen mode

Add LocalizationMiddleware In Kernal.php

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

        ],

Enter fullscreen mode Exit fullscreen mode

Step 5: Create a json File in lang/en.json & lang/bn.json
bn for bangla and en for english. Always Use Same Key for both language.

en.json

{

    "Home" : "WellCome To My Laravel Localization BLog",
    "Contact" :"0181285****"


}


Enter fullscreen mode Exit fullscreen mode

bn.json

{

    "Home" : "লারাভেল লোকালাইজেশন ব্লগ এ আপনাকে স্বাগতম",
    "Contact" :"০১৮১২৮৫****"

}


Enter fullscreen mode Exit fullscreen mode

Call Lang file in Blade

  <p>{{ __('Home') }}</p>
  <p>{{ __('Contact') }}</p>
Enter fullscreen mode Exit fullscreen mode

Language Shifting Toogle Button Code

 <div class="form-check form-switch d-flex align-items-center gap-2 languge-content">
        <p class="language-text">English</p>
        <div>
            <input class="form-check-input language-btn ms-0 mt-0 languageChange" id="languageChange"
                type="checkbox" {{ Session::get('locale') == 'bn' ? 'checked' : '' }} />
        </div>
        <p class="language-text">বাংলা</p>
    </div>
Enter fullscreen mode Exit fullscreen mode

Get Value from Toogle Button and Pass Value to Change Language

  <script>
    $('.languageChange').click(function() {
        var mode = $(this).prop('checked');
        if (mode == true) {
            var langVal = 'bn';
        } else {
            var langVal = 'en';
        }

        $.ajax({
            type: 'GET',
            url: '/lang/' + langVal,
            success: function(data) {
                location.reload();
                console.log(langVal);

            },
            error: function(data) {
                console.log('Something went wrong.');
            }
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Here Is full Code
Step 6 : Create a blade file home.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Localization Practice</title>
  <style>
    /* Define styles for the header and toggle button */
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #333;
      color: #fff;
      padding: 10px;
    }

    #toggle {
      background-color: #fff;
      color: #333;
      border: none;
      padding: 5px 10px;
      cursor: pointer;
    }
  </style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js"
    integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
    <link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css"
    integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />

</head>
<body>
  <header>
    <h1>Localization Practice</h1>
    <div class="form-check form-switch d-flex align-items-center gap-2 languge-content">
        <p class="language-text">English</p>
        <div>
            <input class="form-check-input language-btn ms-0 mt-0 languageChange" id="languageChange"
                type="checkbox" {{ Session::get('locale') == 'bn' ? 'checked' : '' }} />
        </div>
        <p class="language-text">বাংলা</p>
    </div>  </header>

  <main>
    <p>{{ __('Home') }}</p>
    <p>{{ __('Contact') }}</p>


  </main>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>

  <script>
    $('.languageChange').click(function() {
        var mode = $(this).prop('checked');
        if (mode == true) {
            var langVal = 'bn';
        } else {
            var langVal = 'en';
        }

        $.ajax({
            type: 'GET',
            url: '/lang/' + langVal,
            success: function(data) {
                location.reload();
                console.log(langVal);

            },
            error: function(data) {
                console.log('Something went wrong.');
            }
        });
    });
</script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Here is The Visual

Image description

Image description

Top comments (4)

Collapse
 
tarequr profile image
Tarequr Rahman Sabbir

It' very helpful.

Collapse
 
muftehedul profile image
muftehedul

thanks for sharing, it will be very helpful for us.

Collapse
 
soemoesmarttoy profile image
soemoesmarttoy

Thank you for the post. It is very helpful.

Collapse
 
soemoesmarttoy profile image
soemoesmarttoy

Have to put
use App;
use Session;

in app/Http/Middleware/Localization.php and app/Http/Controllers/LocalizationController.php