Middleware for localization

Creating a middleware file

php artisan make:middleware Localization

Add middleware to app/Http/Kernel.php

    protected $routeMiddleware = [

        'localization' => \App\Http\Middleware\Localization::class,
    ];

Apply middleware in route.php

Route::get('/', '[email protected]')->middleware('localization');

Middleware

    public function handle($request, Closure $next)
    {
        //$locale = App::getLocale();
        //logg($locale);
        $locale = $request->input('locale');
        //logg($locale);
        if($locale != false){
            session('locale', $locale);
            App()->setLocale($locale);
        }else if(session('locale') != false){
            App()->setLocale(session()->get('locale'));
        }

        return $next($request);
    }

Note

  1. Constructor of a controller will be execute before route, middleware and session.

Reference

  1. https://laravel.com/docs/5.4/middleware