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

screenager's avatar

Session variables unknown during building of menu middleware

I want my webmaster to be able to impersonate as another user. Therefore I have a form with a controller to write a session variable containing the ID he is impersonating. In my authentication middleware I check for the presence of this session variable:

class AuthenticateOnceWithBasicAuth {
  public function handle($request, Closure $next) {
    if (Session::has('simulate_as')) {
      $username = Session::get('simulate_as');
    } 
    else {
      $username = $_SERVER["REMOTE_USER"]; // fallback on single login authentication
    }
    $user = User::where('username', $username)->first();

    Auth::login($user);

    return $next($request);
  }
}

Problem is that when using the menu middleware, the session is not yet sent to the browser. Should I change something in the order of my items in kernel.php?

protected $middleware = [
  \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
  \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
  \App\Http\Middleware\MenuMiddleware::class,
  \Illuminate\Session\Middleware\StartSession::class,
  \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
0 likes
4 replies
pmall's avatar
pmall
Best Answer
Level 56

Session is started by a middleware. Put your middleware after the session middleware.

screenager's avatar

Forgot to mention that I tried that

protected $middleware = [
  \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
  \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
  \Illuminate\Session\Middleware\StartSession::class,
  \Illuminate\View\Middleware\ShareErrorsFromSession::class,
  \App\Http\Middleware\MenuMiddleware::class,
];

No effect, the session is not detected and the default user is taken during the MenuMiddleware build

pmall's avatar

In your last post your middleware is still above the session middleware.

Please or to participate in this conversation.