Check a session variable before laravel auth middleware

1.2k views Asked by At

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.

1

There are 1 answers

1
Alexey Mezenin On

The problem is you're trying to save data to config after the request is handled by the application (see Before & After Middleware section). Setting up config after request was handled by the app just doesn't make any sense.

Syntax should be:

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

    $response = $next($request);

    return $response;

}