Skip to content

Instantly share code, notes, and snippets.

@xarmengol
Last active February 6, 2024 01:46
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xarmengol/1fcb39677ad940fb5dcfe5450773adc6 to your computer and use it in GitHub Desktop.
Save xarmengol/1fcb39677ad940fb5dcfe5450773adc6 to your computer and use it in GitHub Desktop.
Set locale for authenticated users in laravel

Intro

What we want to do is to set the locales of a laravel 5.6 application, by depending of the language of the authenticated user. We store the language preferences of a user on the database, in the users table.

Steps

Create a new Middleware:

php artisan make:middleware AuthUserSetLocale

With this middleware, we check if there is an authenticated user, in which case, we set it's language as App locale. Middleware content:

<?php

namespace App\Http\Middleware;

use Closure;

class AuthUserSetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (\Auth::check()) {
            \App::setLocale(\Auth::user()->language);
        }

        return $next($request);
    }
}

Last step is to register the new middleware in our Kernel app (app/Http/Kernel.php file):

  protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \App\Http\Middleware\AuthUserSetLocale::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
@haleyngonadi
Copy link

Thank you!

@hendrixthecoder
Copy link

This helped so much! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment