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

varovas's avatar

SESSION DOESN'T WORK IN MIDDLEWARE

Hello again,

I Have an issue, that session doesnt work in middleware in my laravel project.

Language Middleware handle:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Redirector;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Session;

class Language {

    public function __construct(Application $app, Redirector $redirector, Request $request) {
        $this->app = $app;
        $this->redirector = $redirector;
        $this->request = $request;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        // Make sure current locale exists.
        if (Session::has('lang')) :
            $locale = Session::get('lang');
        else :
            $locale = $this->app->config->get('app.fallback_locale');
        endif;

        $this->app->setLocale($locale);

        return $next($request);
    }

}

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 = [
        \App\Http\Middleware\Language::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

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

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

Any ideas?

0 likes
18 replies
topvillas's avatar

Not sure but I'm guessing the StartSession middleware hasn't booted before you're trying to use your Language middleware.

1 like
Msahirullah's avatar

Thank you Dude :):). It's works for me by putting '\Illuminate\Session\Middleware\StartSession::class," top of the "middlewaregroup" and "middleware web".

3 likes
RonB1985's avatar
RonB1985
Best Answer
Level 18

This should work:

        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \App\Http\Middleware\Language::class,
        ],
6 likes
vpower's avatar

You could also try:

$request->session()->get('lang');
RonB1985's avatar

You're welcome, had the same issue some time ago :)

thewruck's avatar

With Laravel 11, you how do you manipulate Middleware order since it have been moved out of the kernel.php file and buried in the vendor structure?

aminsbeity's avatar

@Snapey thank you for your feedback noting that i did check the solution but still not working below you can find 2 files

1- app.php file located in bootstrap

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;


use Illuminate\Session\Middleware\StartSession;
use App\Http\Middleware\CommonData;


return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(StartSession::class);
        $middleware->append(CommonData::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

2-custom middleware that i create it ( CommonData.php classs )

my problem still exist which is: ! session()->has('iso') always true means session in CommonData middleware is not working because session has iso value

appreciate your support

Snapey's avatar

@aminsbeity Why don't you start your own question and describe your issue fully?

You don't need to mess with StartSession middleware, it is already applied to all web routes.

You can list all middleware and I think, in the order they are applied, by the following command

php artisan -vv route:list

for example;

  GET|HEAD   dashboard .............................................................................................. dashboard
             ⇂ Illuminate\Cookie\Middleware\EncryptCookies
             ⇂ Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse
             ⇂ Illuminate\Session\Middleware\StartSession
             ⇂ Illuminate\View\Middleware\ShareErrorsFromSession
             ⇂ Illuminate\Foundation\Http\Middleware\ValidateCsrfToken
             ⇂ Illuminate\Auth\Middleware\Authenticate
             ⇂ Illuminate\Routing\Middleware\SubstituteBindings
             ⇂ Illuminate\Auth\Middleware\EnsureEmailIsVerified

check that your middleware appears AFTER start session

aminsbeity's avatar

@Snapey my issue is that ! session()->has('iso') always true in CommonData middleware. i did follow your feedback and below you can find 2 files 1- app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;



use App\Http\Middleware\CommonData;


return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(CommonData::class);
        
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();


2: CommonData middleware

3: php artisan -vv route:list

GET|HEAD       / ...................
                 ⇂ web
  GET|HEAD       about ...........................
                 ⇂ web
  GET|HEAD       apartment ..........................
                 ⇂ web
  GET|HEAD       apartments ..........................
                 ⇂ web
  GET|HEAD       buildings ......................
                 ⇂ web
  GET|HEAD       contact .....................
                 ⇂ web
  GET|HEAD       language/{iso} ................
                 ⇂ web
  GET|HEAD       projects ...............
                 ⇂ web
  GET|HEAD       properties ................
                 ⇂ web
  GET|HEAD       services ..................
                 ⇂ web
  GET|HEAD       storage/{path} ................. storage.local
  GET|HEAD       up .....................

                                                                                                                                                   Showing [12] routes




dkulagin's avatar

I encountered the same issue. The solution was to replace:

$middleware->append(MyCustomMiddleware::class);

with:

$middleware->appendToGroup('web', MyCustomMiddleware::class);

in the bootstrap/app.php file.

It's unfortunate that the official Laravel 12 documentation doesn't highlight this nuance in the "Registering Middleware" → "Global Middleware" section (https://laravel.com/docs/12.x/middleware#global-middleware), where it suggests using the append method.

1 like
dkulagin's avatar

@ghabe Thanks for sharing! I'm new to Laravel and taking every opportunity to learn the Laravel way.

Please or to participate in this conversation.