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

silverxjohn's avatar

Session variables missing after fail logging in.

So, I have this middleware called CheckOneUser it has this code.

public function handle($request, Closure $next)
    {
        $response = $next($request);

        return $response;
    }

    public function terminate($request, $response)
    {
        if (! \Auth::check())
            return;

        $user = \Auth::user();

        if (!$user->session_id) {
            $user->session_id = \Session::getId();
            $user->last_activity = Carbon::now();
            $user->save();
        }
        else {
            $last_session = \Session::getHandler()->read($user->session_id);

            if ($last_session) {
                \Auth::logout();
                \Session::getHandler()->destroy(\Session::getId());
                \Session::flash('session', 'Someone already logged in.');
                return redirect()->route('login', ['session' => 'Someone already logged in.']);
            }
        }
    }

I want to happen is that when the user happens to login then someone is already logged in. I will return a message to my view. My view has this line where I can check if it has session.

                        {{session()->has('session') ? session()->get('session') : 'sadsa'}}

And my web.php looks like this.

Route::group(['middleware' => ['checkoneuser']], function () {
    Route::post('login', 'Auth\LoginController@login');

    Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
});

I registered that middleware to my Kernel. It is working as intended user can't logged in but I can't seem to pass that session variable so that I can send it to my view.

0 likes
3 replies
Borisu's avatar

You're using the flash function, which will show the flash message only to the next view in the chain. Usually using middleware you go through a couple of layers and the flash gets lost. Try saving the message to the session instead of flashing it. If it works you'll know it's a problem with the amount of layers you have in your app...

2 likes
silverxjohn's avatar

@Borisu I've already fixed it, by using put not flash and I've make it as a after middleware. And I've put on the terminate method forgetting the session variable and at the first request so that it will clear the session variable when successful login and first load. Thanks!

Borisu's avatar

Great! Consider marking the question as done ;)

Please or to participate in this conversation.