During a process to build a web application, it can sometime unavoidable to deal with localization of the application. Having multiple localizations can be beneficial to your web application as users can surf in their preferred language.

If you are using Laravel framework to build the web application, you might be wondering on how to properly set up multiple localization on your web application. There are multiple ways of doing it, but we will focus here on changing locale without using prefix in the URI segment.

You will need to use session in conjunction with a middleware. All you need is a controller and a middleware. Make sure you have appropriate locale file in resources\lang\ directory.

App\Http\Controllers\LangController.php Method

class LangController extends Controller
{
    public function setLang($locale)
    {
        // 1. store selected locale
        Session::put('my_project.locale', $locale);

        return back();
    }
}

App\Http\Middleware\Language.php Method

class LocaleMiddleware
{
    public function handle($request, Closure $next)
    {
        $default = config('app.locale');

        // 2. retrieve selected locale if exist (otherwise return the default)
        $locale = Session::get('my_project.locale', $default);

        // 3. set the locale
        App::setLocale($locale);

        return $next($request);
    }
}

Next, you will need to register the middleware in the kernel, under route middleware.

App\Kernel.php

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'lang' => \App\Http\Middleware\Language::class,
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Lastly, remember to register the middleware on the controller where you want localization to happen.

Leave a comment