Coding Notes Laravel

Set And Store Locale In Laravel 5.6 Using Middleware

I used this simple way to set and store the locale setting in Laravel 5.6 using middlewares. The code is pretty basic, if there’s a locale in the request then set the setting in session based on the parameter.

App\Http\Middleware\SetLocale.php

<?php

namespace App\Http\Middleware;

use Closure;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->has('locale')) {
            if (in_array(strtolower($request->locale), ['en', 'de', 'ko', 'jp', 'km', 'th', 'vi'])) {
                session()->put('locale', $request->locale);
            } else {
                session()->put('locale', 'en');
            }
        }

        if(session()->has('locale')) {
            app()->setLocale(session('locale'));
        }

        return $next($request);
    }
}

App\Http\Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [

            \App\Http\Middleware\SetLocale::class,

        ],
        'api' => [
            'throttle:60,1',
            'bindings'
        ],
    ];

}

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.