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

mojosef's avatar

Check a session variable before laravel auth middleware

I need to check a session variable to set a config item in laravel. I need this to run before the auth middleware though. I've tried all sorts of configurations to get it working but no matter what, auth runs before I set the database so it fails to find the user.

This is what I have so far:

Kernal.php

'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,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\CheckTenant::class,
    ],

CheckTenant:

public function handle($request, Closure $next)
 {
    
  if(session()->has('database')){
        //set db in config for eloquent
        Config::set('database.connections.mysql.database', session('database'));
    }

    $response = $next($request);

    return $response;

 }

My route:

Route::group(['middleware' => 'auth'], function () {
    
    // All my routes that needs a logged in user
    Route::get('/dashboard', function () {
        return view('jobs.index');
    });

});

So basically I just need to set a config item at each request before it checks authentication.

Any help would be really appreciated.

0 likes
2 replies
sandersjj's avatar

It could be that the order of the middleware makes a difference. Have you tried to put the middleware statement as the first item in the array in kernel.php?

mojosef's avatar

I have yeah, the auth middleware always seems to take precedence. I've wrapped the auth route group in its own group and it still seems to go first. I guess it kind of makes sense to do that.

Please or to participate in this conversation.