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

dschumbi's avatar

session object before and after login

dear all,

i´m saving an object in a session. but after the user logs in, the object seems to be gone. any ideas how i can keep the object, so that it´s available also after the login and e.g. can be persisted in a database?

thx in advance!

br heiko

0 likes
2 replies
Snapey's avatar

The default LoginController.php uses the trait AuthenticatesUsers.php

This contains

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

my guess would be that $request->session()->regenerate(); creates a new session that does not have any of the data of the previous session.

I don't advise that you remove this but you could pull the data you need into the controller, regenerate the session and then store the session variables again.

Since the method above is in a trait, you can duplicate this code into your LoginController and then modify it, e.g.

LoginController.php

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $cart = session('cart');

        $request->session()->regenerate();

        session(['cart' => $cart]);

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

2 likes
elham's avatar

The default LoginController.php uses the trait AuthenticatesUsers.php . so copy this code to LoginController.php to overwrite it.

/** * Send the response after the user was authenticated. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */

public function logout(Request $request) { $data = session()->get('cart'); $this->guard()->logout();

    $request->session()->invalidate();
    $request->session()->regenerate();
    session()->put('cart', $data);
    return $this->loggedOut($request) ?: redirect('/');
}
1 like

Please or to participate in this conversation.