menu

Localization

Introduction

Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. Language strings are stored in files within the resources/lang directory. Within this directory there should be a subdirectory for each language supported by the application:

  
    resources/
    ├── lang/
    |   ├── en/
    |   |   ├── locale.php
    |   ├── de/
    |   |   ├── locale.php 
        

All language files return an array of keyed strings. For example:

  
    <?php

    return [
        "Dashboard" => "Instrumententafel",
        "Analytics" => "Analytics",
    ];
      
Configuring The Locale

The default language for your application is stored in the config/app.php configuration file. You may modify this value to suit the needs of your application. You may also change the active language at runtime using the setLocale method on the App facade:

  
    Route::get('welcome/{locale}', function ($locale) {
      App::setLocale($locale);
  
      //
  });
      

You may configure a "fallback language", which will be used when the active language does not contain a given translation string. Like the default language, the fallback language is also configured in the config/app.php configuration file:

  
    'fallback_locale' => 'en',
      
Defining Translation Strings

Typically, translation strings are stored in files within the resources/lang directory. Within this directory there should be a subdirectory for each language supported by the application:

Retrieving Translation Strings

You may retrieve lines from language files using the __ helper function. The __ method accepts the file and key of the translation string as its first argument. For example, let's retrieve the welcome translation string from the resources/lang/en/locale.php language file:

  
    echo __('locale.welcome');
    

If you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive:

  
    {{ __('messages.welcome') }}

    @lang('messages.welcome')
      

Now all set to work localization in simple project.

Localization in Materialize Laravel

In Materialize laravel, We provide a dropdown to switch language you can find it in the navbar. How does it work? When we select a language from dropdown-menu we call a Route which calls a controller's function which then put selected language in session. We have created a middleware that sets the localization value from the session variable. We set the session's lifetime 30min in the .env file. It sounds a little messy. Let's find out how to do it.

We have to create a Controller to check selected language is available or not in our template and then save it to session variable. Run below command.

  
    php artisan make:controller LanguageController
        

Use the below code in LanguageController file in App/Http/Controllers.

  
    <?php

      namespace App\Http\Controllers;

      use App\Http\Controllers\Controller;
      use Illuminate\Http\Request;

      class LanguageController extends Controller
      {
          //
          public function swap($locale){
              // available language in template array
              $availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt'];
              // check for existing language
              if(array_key_exists($locale,$availLocale)){
                  session()->put('locale',$locale);
              }
              return redirect()->back();
          }
    }
        

We have to define Route for language switching in routes/web.php file.

  
    <?php
      use App\Http\Controllers\LanguageController;
    // locale Route
    Route::get('lang/{locale}',[LanguageController::class,'swap']);
        

Now we need a middleware to set app()->setLocale() variable gloabaly. Run below cammand to create a middleware.

  
    php artisan make:middleware LocaleMiddleware
          

You can find this middleware in App\Http\Middleware

  
    <?php

      namespace App\Http\Middleware;

      use Closure;

      class LocaleMiddleware
      {
          /**
          * Handle an incoming request.
          *
          * @param  \Illuminate\Http\Request  $request
          * @param  \Closure  $next
          * @return mixed
          */
          public function handle($request, Closure $next)
          {  
              // available language in template array
              $availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt'];

              // Locale is enabled and allowed to be change
              if(session()->has('locale') && array_key_exists(session()->get('locale'),$availLocale)){
                  // Set the Laravel locale
                  app()->setLocale(session()->get('locale'));
              }
              return $next($request);
          }
    }
        

You must have to mention middleware in the App\Http\kernel.php file. Use the \App\Http\Middleware\LocaleMiddleware::class, line in kernel.php file.

  
    protected $middlewareGroups = [
    'web' => [
    
        \App\Http\Middleware\LocaleMiddleware::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];
        

Now we have to set the view. We provide language switch dropdown in navabar.blade.php.

  
    <a class="dropdown-toggle nav-link" id="dropdown-flag" href="#" data-toggle="dropdown"
          aria-haspopup="true" aria-expanded="false">
          <i class="flag-icon flag-icon-us"></i>
          <span class="selected-language">English</span>
        </a>
        <div class="dropdown-menu" aria-labelledby="dropdown-flag">
          <a class="dropdown-item" href="{{url('lang/en')}}" data-language="en">
            <i class="flag-icon flag-icon-us"></i>English
          </a>
          <a class="dropdown-item" href="{{url('lang/fr')}}" data-language="fr">
            <i class="flag-icon flag-icon-fr"></i>French
          </a>
          <a class="dropdown-item" href="{{url('lang/de')}}" data-language="de">
            <i class="flag-icon flag-icon-de"></i>German
          </a>
          <a class="dropdown-item" href="{{url('lang/pt')}}" data-language="pt">
            <i class="flag-icon flag-icon-pt"></i>Portuguese
          </a>
        </div>
        

We need to retrieve lines from language files using the __ helper function. The __ method accepts the file and key of the translation string as its first argument. We are using the Blade templating engine, We use the {{ }} syntax to echo the translation string or use the @lang directive:

Resources/views/panels

sidebar.blade.php

  
    <div class="main-menu-content">
      <ul class="navigation navigation-main" id="main-menu-navigation" data-menu="menu-navigation">
        {{-- Foreach menu item starts --}}
        @if(isset($menuData[0]))
        @foreach($menuData[0]->menu as $menu)
        @if(isset($menu->navheader))
        
        @else
        {{-- Add Custom Class with nav-item --}}
        @php
        $custom_classes = "";
        if(isset($menu->classlist)) {
        $custom_classes = $menu->classlist;
        }
        $translation = "";
        if(isset($menu->i18n)){
        $translation = $menu->i18n;
        }
        @endphp
        <li class="nav-item {{ (request()->is($menu->url)) ? 'active' : '' }} {{ $custom_classes }}">
          <a href="{{ $menu->url }}">
            <i class="{{ $menu->icon }}"></i>
            <span class="menu-title" data-i18n="{{ $translation }}">{{ __('locale.'.$menu->name) }}</span>
            @if (isset($menu->badge))
            <?php $badgeClasses = "badge badge-pill badge-primary float-right" ?>
            <span
              class="{{ isset($menu->badgeClass) ? $menu->badgeClass.' test' : $badgeClasses.' notTest' }} ">{{$menu->badge}}</span>
            @endif
          </a>
          @if(isset($menu->submenu))
          @include('panels/submenu', ['menu' => $menu->submenu])
          @endif
        </li>
        @endif
        @endforeach
        @endif
        {{-- Foreach menu item ends --}}
      </ul>
    <S/div>
</div>
        

submenu.blade.php

  
    {{-- For submenu --}}
      <ul class="menu-content">
          @if(isset($menu))
          @foreach($menu as $submenu)
          <?php
                  $submenuTranslation = "";
                  if(isset($menu->i18n)){
                      $submenuTranslation = $menu->i18n;
                  }
              ?>
          <li class="{{ (request()->is($submenu->url)) ? 'active' : '' }}">
              <a href="{{ $submenu->url }}">
                  <i class="{{ isset($submenu->icon) ? $submenu->icon : "" }}"></i>
                  <span class="menu-title" data-i18n="{{ $submenuTranslation }}">{{ __('locale.'.$submenu->name) }}</span>
              </a>
              @if (isset($submenu->submenu))
              @include('panels/submenu', ['menu' => $submenu->submenu])
              @endif
          </li>
          @endforeach
          @endif
      </ul>
        

HorizontalMenu.blade.php

  
        <!-- Horizontal menu content-->
    <div class="navbar-container main-menu-content" data-menu="menu-container">
      <ul class="nav navbar-nav" id="main-menu-navigation" data-menu="menu-navigation">
        {{-- Foreach menu item starts --}}
        @if(isset($menuData[1]))
        @foreach($menuData[1]->menu as $menu)
        @php
        $custom_classes = "";
        if(isset($menu->classlist)) {
        $custom_classes = $menu->classlist;
        }
        $translation = "";
        if(isset($menu->i18n)){
        $translation = $menu->i18n;
        }
        @endphp
        <li class="dropdown nav-item {{ (request()->is($menu->url)) ? 'active' : '' }} {{ $custom_classes }}"
          data-menu="dropdown">
          <a href="{{ $menu->url }}" class="dropdown-toggle nav-link" data-toggle="dropdown">
            <i class="{{ $menu->icon }}"></i>
            <span data-i18n="{{ $translation }}">{{ __('locale.'.$menu->name) }}</span>
          </a>
          @if(isset($menu->submenu))
          @include('panels/horizontalSubmenu', ['menu' => $menu->submenu])
          @endif
        </li>
        @endforeach
        @endif
        {{-- Foreach menu item ends --}}
      </ul>
    </div>
        

horizontalSubmenu.blade.php

  
    {{-- For Horizontal submenu --}}
      <ul class="dropdown-menu">
        @if(isset($menu))
        @foreach($menu as $submenu)
        <?php
      $custom_classes = "";
      if(isset($submenu->classlist)) {
          $custom_classes = $submenu->classlist;
      }
      $submenuTranslation = "";
      if(isset($menu->i18n)){
          $submenuTranslation = $menu->i18n;
      }
        ?>
        <li
          class="{{ (request()->is($submenu->url)) ? 'active' : '' }} {{ (isset($submenu->submenu)) ? "dropdown dropdown-submenu" : '' }} {{ $custom_classes }}">
          <a href="{{ $submenu->url }}" class="dropdown-item {{ (isset($submenu->submenu)) ? "dropdown-toggle" : '' }}"
            {{ (isset($submenu->submenu)) ? 'data-toggle=dropdown' : '' }}>
            <i class="{{ isset($submenu->icon) ? $submenu->icon : "" }}"></i>
            <span data-i18n="{{ $submenuTranslation }}">{{ __('locale.'.$submenu->name) }}</span>
          </a>
          @if (isset($submenu->submenu))
          @include('panels/horizontalSubmenu', ['menu' => $submenu->submenu])
          @endif
        </li>
        @endforeach
        @endif
      </ul>
        

How to add new language?

Step 1: To add a new language in whole template first we need to create a locale.php file in resources/lang/ which return an array with key and value pair.

resources/lang/de/locale.php
  
    <?php

    return [
        "Dashboard" => "Instrumententafel",
        "Analytics" => "Analytics",
        "eCommerce" => "eCommerce",
        "Apps" => "Anwendungen",
        "UI Elements" => "UI Elemente",
        "Forms & Tables" => "Formulare und Tabellen",
        "Pages" => "Seiten",
        "Charts & Maps" => "Karten & Landkarten",
        "Others" => "Andere",
        "Email" => "Email",
      

Step 2: Now we need to mention our new language in controller and middleware which we already created.

App/Http/Controllers/LanguageController.php
  
  // available language in template array
  $availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt']; //mention your new language as key and value pair.
      
App/Http/Middleware/LocaleMiddleware.php
  
    // available language in template array
    $availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt']; //mention your new language as key and value pair.
      

Step 3: If you want to set your new language as default language using configuration variable then you'll need to do below changes.

App/Helpers/helpers.php

Add your new language in allOption array as key and value pair.

  
    // All options available in the template
    $allOptions = [
        'defaultLanguage'=>array('en'=>'en','fr'=>'fr','de'=>'de','pt'=>'pt'),
    ]; 
      

Step 4: Now you can set your new language as default of whole Template.

config/custom.php
  
    <?php
      return [
          'custom' => [
              'defaultLanguage'=>'en',    //en(default)/de/pt/fr here are four optional language provided in theme
          ], 
      

Your new language is successfully added, Now it's ready to use.

How to remove existing language?

Step 1: To remove a existing language in whole template first we need to delete language folder from resources/lang/.


  resources/
  ├── lang/
  |   ├── en/
  |   |   ├── locale.php
  |   ├── de/
  |   |   ├── locale.php

      

Step 2: Now we need to delete existing language in controller and middleware which is already created.

App/Http/Controllers/LanguageController.php

Remove your existing language from the availLocale array.

  
    // available language in template array
  $availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt']; 
      
App/Http/Middleware/LocaleMiddleware.php

Remove your existing language from the availLocale array.

  
    // available language in template array
    $availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt']; 
      

Step 3: You also need to remove this language from helper.php file.

App/Helpers/helpers.php

remove language from the allOption array.

  
    // All options available in the template
    $allOptions = [
        'defaultLanguage'=>array('en'=>'en','fr'=>'fr','de'=>'de','pt'=>'pt'),
    ];
      

Now existing language has been removed from whole template.

;