Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel localization

1. create language file in lang folder
	en.json, jpn.json, ko.json, hi.json..
    jpn.json->{"Log in": "ログイン", "Register": "登録", etc...}
    
2. create controller and middleware for localization
	-> $ php artisan make:middleware Localization
    -> $ php artisan make:controller LocalizationController

3. declare localization middleware in kernel.php
	  protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
           	...
            Localization::class,
        ],
]

4. create route for localization.
	  Route::get('/lang/{locale}', [AppHttpControllersLocalizationController::class,'lang_change'])->name('lang.change');
      
5. In LocalizationController.php
   public function lang_change($locale){
        Session::put("locale",$locale);
        return redirect()->back();
    }
    
6. In localization.php <- middleware file
->  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);    }
}


7. use in blade
	{{__('Log in')}}
    {{__('Register')}}
    
    
8. choose languages from blade
      <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
        <ul class="list-group list">
          <li class="list-group-item border-0">
              <a href="{{route('lang.change','en')}}">English</a>
          </li>
          <li class="list-group-item border-0">
              <a href="{{route('lang.change','jpn')}}">Japanese</a>
          </li>
          <li class="list-group-item border-0">
              <a href="{{route('lang.change','ko')}}">Korea</a>
          </li>
           <li class="list-group-item border-0">
              <a href="{{route('lang.change','hi')}}">Hindi</a>
          </li>
        </ul>
      </div>
 
PREVIOUS NEXT
Tagged: #laravel #localization
ADD COMMENT
Topic
Name
7+3 =