Language change(localization) in Laravel 5.2 dynamically

These are the steps to change the language dynamically in laravel:

1. In the view page of the login add this lines:
<a href="{{ URL::to('lang/en')}}">English</a>&nbsp;<a href="{{ URL::to('lang/ar')}}">العربية</a>&nbsp;<a href="{{ URL::to('lang/hn')}}">हिन्दी</a>

2.In the routes add file add these lines:

Routes:Route::get('lang/{lang}', 'Auth\AuthController@change_language');

3. In the Controller file as specified in the route:
    public function change_language($lang=null){
        //$lang   =   $request->input('language'); //in case you want to give language select in the login form.

        if($lang) {
            App::setLocale($lang);
            Session::put('locale', $lang);
           // Config::set('constants.default_language_id',$lang);
            return Redirect::back();
        }

    }

4. Most important to create a middle ware i.e http/middleware/SetLocale.php

<?php

namespace App\Http\Middleware;

use Closure;
use Session;
use App;
use Config;

class SetLocale
{
    /**
     *
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
     
        if (Session::has('locale')) {
            $locale = Session::get('locale', Config::get('app.locale'));
        } else {
            $locale = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);

            if ($locale != 'ar' && $locale != 'en') {
                $locale = 'en';
            }
        }

        App::setLocale($locale);

        return $next($request);
    }
}    

5.And finally dont forget to register middleware in http/kernel.phpin the $middleware array:
 \App\Http\Middleware\SetLocale::class,

Comments

  1. If you (can) use JSON files to do Laravel localization, then I suggest you check out the localization management platform POEditor.
    This online platform is great for collaborative translation and for automating many processes in the localization workflow.
    Localization is free up to 1000 hosted strings and it is clearly more affordable than other localization platforms for the paid plans.

    ReplyDelete

Post a Comment