Tuesday, 6 July 2021

Change laravel web application default locale dynamically

 To change laravel locale dynamically we can apply different ways.Today I will teach you very easily

and professional way that I use to follow in all my laravel projects.


Step: 1 

Define middleware 

<?php

namespace App\Http\Middleware;

use Closure;
use App;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($requestClosure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}


you can see I have defined  Localization  middleware.Which will check  locale variable in session 

and on each request it will set application locale variable.



Step: 2 

Include middle in kernal.php php 

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Localization::class,
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


 \App\Http\Middleware\Localization::class,


step: 3

Set locale using session variable.For example I have used in web.php

Route::get('changeLocale/{locale}',function($lang){
    if ($lang == "fr") {
        Session::put('locale', 'fr');
    } else {
        Session::put('locale', 'en');
    }
    return redirect()->back();
});

Here you can see i am setting locale variable in two languages english and french.

So requests changeLocale/en and So changeLocale/fr will set locale value.


step: 4 

html code that will allow use to change language and hit above get request.

<li class="eborder-top">
@if( \Session::get('locale') == "fr" )
<a href="{{ url('/changeLocale/en') }}">
<i class="fa fa-key" aria-hidden="true"></i> English
</a>
@else
<a href="{{ url('/changeLocale/fr') }}">
<i class="fa fa-key" aria-hidden="true"></i> French
</a>
@endif
</li>


Above will check locale key in session and based on that it will run the routed and after

running the route it will set the session key locale value.


For any questions or understanding please do contact !

No comments:

Post a Comment

Laravel csrf token mismatch for ajax post request

Error "CSRF Token Mismatch" commonly occurs if tokens do not match in both sessions and sent , and received requests.CSRF token he...