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

beratdogan6's avatar

Updating session user_id without updating session id

I'm having a trouble with my session. I'm building an e-commerce website, people can create cart without login and it will create a session. After that if they want to login I want to update that session with user_id. I can update it but it updating the session id, and my cart has session_id column which doesnt update what should I do?

0 likes
6 replies
beratdogan6's avatar
public function login(LoginUserRequest $request)
    {
        $request->validated($request->only(['email', 'password']));

        if (!Auth::attempt($request->only(['email', 'password']))) {
            return $this->error('Invalid credentials.', 401);
        }

        $user = User::where('email', $request->email)->first();

        $token = $user->createToken('API Token of ' . $user->name)->plainTextToken;

        $request->session()->put('api_token', $token);
        $request->session()->put('user_id', $user->id);

        return $this->success([
            'user' => $user
        ]);
    }

here is my login function

JussiMannisto's avatar

Your hierarchy seems flipped. Carts shouldn't worry about session ids. Instead, sessions should know cart states. That way you can carry the state through login and you'll have no issue when the session id is regenerated.

JussiMannisto's avatar

@beratdogan6 I don't know the details of your implementation. But yes, I would delete the session_id and keep a cart_id in session data.

1 like

Please or to participate in this conversation.