Search code examples
laravel

Language Selector for Laravel 11 with per-session persistence


How to put in language selected by the user in Laravel 11 in a persistent way, that is to say, that while the visitor or user remains on the page and once selected a language remains in that language even if they change the page?


Solution

  • https://github.com/ShurGith/Localizacion

    Console

    • Install language package.
    composer require laravel-lang/common --dev
    php artisan lang:add es
    php artisan lang:add en
    php artisan lang:update
    

    App/Http/Controllers/LanguageController.php (new file)

    • Create a new controller with this code.
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Redirect;
    use Illuminate\Support\Facades\Session;
    
    class LanguageController extends Controller
    {
        public function switch($lang)
        {
                Session::put([
                    'applocale' => $lang,
                    'locale' => $lang,
                ]);
                return Redirect::back();
        }
    }
    

    App\Http\Middleware\Language.php (new file)

    • Create a nuew middleware with this code.
    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Session;
    use Symfony\Component\HttpFoundation\Response;
    
    class Language
    {
        public function handle(Request $request, Closure $next): Response
        {
            $langSesion = Session::get('applocale');
            array_key_exists($langSesion, config('languages')) ? App::setLocale($langSesion) : App::setLocale(Config('app.fallback_locale'));
    
            return $next($request);
        }
    }
    

    bootstrap\app.php

    • In case you have not edited it before, the "app.php" file in the bootstrap folder will look like this:
    <?php
    
    use App\Http\Middleware\Language;
    use Illuminate\Foundation\Application;
    use Illuminate\Foundation\Configuration\Exceptions;
    use Illuminate\Foundation\Configuration\Middleware;
    
    return Application::configure(basePath: dirname(__DIR__))
        ->withRouting(
            web: __DIR__ . '/../routes/web.php',
            commands: __DIR__ . '/../routes/console.php',
            health: '/up',
        )
        ->withMiddleware(function (Middleware $middleware) {
            $middleware->web(append: [Language::class]);
        })
        ->withExceptions(function (Exceptions $exceptions) {
            //
        })->create();
    
    

    config\languages.php (new file)

    • Create a new file called "languages.php" into the config folder. (*in this sample there are only two languages)
    return $idiomas = [
        'en' => "English",
        'es' => "Español",
    ];
    

    resources\views_partials\lang.blade.php (new file)

    • File menu, verifying that the language passed by GET is among the supported languages, otherwise it will return the default pre-determined language.
    @props([
        'idioma' => array_key_exists(session('locale'),config('languages')) ? session('locale') : Config('app.locale'),
    ])
    <ul>
    @foreach (config('languages') as $key => $value)
        @if ($key != $idioma)
        <li>
            <a class="inline-flex rounded bg-indigo-500 px-6 py-2 text-lg text-white"
            href="{{ route('lang', $key) }}">{{ $value }}</a>
        </li>
        @endif
    @endforeach
    </ul>