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

t0berius's avatar

set session before middleware is called

Inside the SettingsController a user can activate a 2 factor email login / TOTP login:

 //set two factor auth if user has activated email based 2 factor auth
    if($request->twofactor_type == 1 && Auth::user()->twofactor_type != 1)
        session([
            '2fa_auth'  => true,
        ]);

    return redirect()->back()->withSuccess(__('settings.changeSuccess'));

Because after the first initial activation of this I don't want to annoy the current user with this, since he is already logged into and it's the first time he has activated the 2 factor login I try to set the session to '2fa_auth' => true,.

It seems like my middleware TwoFactorAuth is triggered before the session data is written.

TwoFactorAuth middleware:

    //check if user has activated the 2factor login
    if(Auth::user()['twofactor_type'] > 0){

        //email based 2 factor auth
        if(Auth::user()['twofactor_type'] == 1){

            //is this user already authenticated?
            if(session('2fa_auth') == true){
                $request->session()->forget('2fURL');
                return $next($request);
            }

Any idea how I can make sure the session data is stored and user is not forced by the middleware to enter 2 factor auth code when he has activated the 2 factor auth the first time?

0 likes
3 replies
slev1n's avatar

@t0berius session retrieveing and parsing middleware stored in app/Http/Kernel.php -> protected $middlewareGroups array (\Illuminate\Session\Middleware\StartSession::class)

Check that your middleware works after all that middlewares executed.

t0berius's avatar

@slev1n I don't understand your reply, the middleware itself works fine.

slev1n's avatar

sorry, thought about another issue.

Middleware execution order:

1. app/Http/Kernel.php -> protected $middleware (globals)
2. app/Providers/RouteServiceProvider.php:  
	Route::middleware('web') // see list from Kernel
                ->group(base_path('routes/web.php'));
	Route::middleware('web') // see list in Kernel.php
                ->group(base_path('routes/web.php'));

            Route::prefix('api')
                ->middleware('api') // see list in Kernel.php
                ->group(base_path('routes/api.php'));
3. your custom from web.php or api.php -> Route::middleware(['some1', 'some2']);

check this order, your middleware should be in route definition.

Be sure that your middleware executes after \Illuminate\Session\Middleware\StartSession::class, from the Kernel.php -> $middlewareGroups, because StartSession::class retrieves and parse session (your changes wont be saved in session if you try session()->put() before actually session was parsed by system).

Please or to participate in this conversation.