Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Angela210's avatar

Global Middleware Access Session Object

Curious if anyone was able to do this in Laravel 11?

I am trying to set the locale and found out on a 404 that the web-based middleware is never run; it is skipped because it is not a valid route.

So I am trying to do it in global middleware.

Any help is greatly appreciated!

0 likes
4 replies
LaryAI's avatar
Level 58

In Laravel, middleware can be used to handle various tasks, including setting the locale. However, accessing the session in global middleware can be tricky, especially when dealing with routes that don't exist (like a 404 error).

To access the session in global middleware, you need to ensure that the session is started before your middleware runs. Here's a step-by-step solution:

  1. Create a Global Middleware:

    First, create a new middleware using the Artisan command:

    php artisan make:middleware SetLocale
    
  2. Modify the Middleware:

    In your SetLocale middleware, you can access the session and set the locale. Here's an example of how you might do it:

    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Session;
    
    class SetLocale
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // Check if the session has a 'locale' key
            if (Session::has('locale')) {
                // Set the application locale
                App::setLocale(Session::get('locale'));
            }
    
            return $next($request);
        }
    }
    
  3. Register the Middleware:

    To ensure this middleware runs globally, you need to register it in the app/Http/Kernel.php file. Add it to the $middleware array:

    protected $middleware = [
        // Other middleware
        \App\Http\Middleware\SetLocale::class,
    ];
    
  4. Ensure Session Middleware is Loaded:

    The session middleware should be loaded before your custom middleware. Laravel's default session middleware is usually included in the web middleware group. However, since you're dealing with global middleware, ensure that the session is started by including \Illuminate\Session\Middleware\StartSession::class in the $middleware array if it's not already there.

  5. Handling 404 Errors:

    Since 404 errors might bypass the web middleware group, having your locale setting middleware globally ensures it runs even on non-existent routes.

By following these steps, you should be able to set the locale using session data in a global middleware, even when handling 404 errors.

Angela210's avatar

This is my code...I can grab the session object with no problems. But storing the locale is not working. When it comes back the Session Object array is blank. Session::all() returns nothing in the array after it is set.

Sorry for the bad formatting how do I get my code to code format, so it is easier to read for you all?

namespace App\Http\Middleware;

use App\Enums\Languages; use Closure; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Session;

class SetLocale { public function handle($request, Closure $next) { if (Auth::check() and Auth::user()->lang) { App::setLocale(Auth::user()->lang); } elseif (Session::has('locale')) { App::setLocale(Session::get('locale')); Session::put('locale_text', Languages::from(Session::get('locale'))->label()); } else{ App::setLocale(config('app.fallback_locale')); Session::put('locale',config('app.fallback_locale') ); Session::put('locale_text', Languages::from(Session::get('locale'))->label()); }

    return $next($request);
}

}

Naman178's avatar

Solution: Using Global Middleware You can create a middleware that sets the locale based on the request and register it globally.

  1. Create a Middleware php artisan make:middleware SetLocale

  2. Update the Middleware Modify the generated middleware (app/Http/Middleware/SetLocale.php) to set the locale:

    namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; class SetLocale { public function handle(Request $request, Closure $next) { // Get the locale from session, request, or default $locale = $request->getPreferredLanguage(['en', 'fr', 'es', 'de']) ?? 'en'; // Set application locale App::setLocale($locale); return $next($request); } }

  3. Register Middleware Globally In Laravel 11, middleware registration happens in app/Http/Kernel.php. Open the file and add your middleware to the $middleware array: protected $middleware = [ \App\Http\Middleware\SetLocale::class, ];

  4. Clear Cache and Test php artisan config:clear php artisan cache:clear

Please or to participate in this conversation.