Skip to content

Instantly share code, notes, and snippets.

@Neeraj1005
Last active August 11, 2021 12:29
Show Gist options
  • Save Neeraj1005/32af857943b6547e95a6ac28766fad79 to your computer and use it in GitHub Desktop.
Save Neeraj1005/32af857943b6547e95a6ac28766fad79 to your computer and use it in GitHub Desktop.
Adding localization in laravel app. (Multiple language support)

How you can setup multilanguage in your laravel app

Step1:

  • first, add a languages array in config/app.php
 'languages' => [
      'en' => 'English',
      'hi' => 'Hindi',
  ],

step2:

  • second, inside your layout navigation add this code
@if(count(config('app.languages')) > 1)
    <li class="nav-item dropdown d-md-down-none">
        <a class="nav-link" data-toggle="dropdown" href="#" role="button" aria-haspopup="true"
            aria-expanded="false">
            {{ strtoupper(app()->getLocale()) }}
        </a>
        <div class="dropdown-menu dropdown-menu-right">
            @foreach(config('app.languages') as $langLocale => $langName)
                <a class="dropdown-item" href="{{ url()->current() }}?change_language={{ $langLocale }}">
                    {{ strtoupper($langLocale) }} ({{ $langName }})
                </a>
            @endforeach
        </div>
    </li>
@endif

step3: Create Middleware For setLocale

  • php artisan make:middleware SetLocale
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (request('change_language')) {
            session()->put('language', request('change_language'));
            $language = request('change_language');
        } elseif (session('language')) {
            $language = session('language');
        } elseif (config('app.locale')) {
            $language = config('app.locale');
        }

        if (isset($language) && config('app.languages.' . $language)) {
            app()->setLocale($language);
        }
        
        return $next($request);
    }
}

Step3.1: Register middleware

  • After creating the middleware register it into app/Http/kenel.php
protected $middlewareGroups = [
  'web' => [
      ......
      ......
      \App\Http\Middleware\SetLocale::class,
  ],

Step4: Add lang Folder inside resoures/lang/

  • After follow the above steps, create your language folder inside resources/lang/hi, resources/lang/en etc...
  • create directory according to your needs

Now Run your project and check

Note: This gist is followed using this link, for more detail watch this video click_here

Screenshot

Click Here to see output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment