Session variables missing after fail logging in.

Published 5 months ago by silverxjohn

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())

        $user = \Auth::user();

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

            if ($last_session) {
                \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\[email protected]');

    Route::get('login', 'Auth\[email protected]')->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.

5 months ago (108,130 XP)

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...


@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!

5 months ago (108,130 XP)

Great! Consider marking the question as done ;)

Please sign in or create an account to participate in this conversation.