Saturday, 5 December 2020

How to create localization in laravel without url changing?

 Step 1. Create a route as shown below.

Route::get('en', function() { session(['locale' => 'en']); return back(); });
Route::get('hi', function() { session(['locale' => 'hi']); return back(); });

Step 2. Create a middleware named SetLocale and write the code as below.
            php artisan make:middleware SetLocale

<?php

namespace App\Http\Middleware;
use App;
use Closure;
class SetLocale
{  
    protected $supported_languages = ['en', 'hi'];     
    public function handle($request, Closure $next)
    {
        if(!session()->has('locale')) {
            session(['locale' => $request->getPreferredLanguage($this->supported_languages)]);
        }
        app()->setLocale(session('locale'));
        return $next($request);
    }
}
 

Step 3. Add the SetLocale middleware in kernal.php

In the  protected $middlewareGroups = [
        'web' => [

                        \App\Http\Middleware\SetLocale::class, 

Step 4.Update the app.blade for navigation

<ul class="navbar-nav ml-auto">
          <!-- Authentication Links -->
          @guest
        ...
          @endif
          @else
      ...
          @endguest
         <li class="nav-item dropdown "> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Language </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item " href="{{url('en')}}">English</a>
            <div class="dropdown-divider"></div>
              <a class="dropdown-item" href="{{url('hi')}}">Hindi</a> </div>
          </li>

        </ul> 

It will look like this. 

Step 5. Create a folder name hi in resources\lang, now create a file named labels.php in hi folder through notepad and set the encoding =  UTF-8

<?php
return [   

'E-Mail Address' => 'ईमेल पता',
    'Reset Password' =>'पासवर्ड रीसेट',
    'Password' =>'पासवर्ड',
    'Login' => 'लॉग इन',
    'Remember Me' => 'मुझे याद रखें',
    'Reset Link' => 'पासवर्ड रीसेट लिंक भेजें',
    'Forgot you password' => 'आप पासवर्ड भूल गए',

]; 

Now to print the value {{  __('labels.Reset Password') }} or  {!!  __('labels.Reset Password') !!}

Thanks. 


 


No comments:

Post a Comment

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...