eriktobben's avatar

Best way of keeping Cart active after logout

Hi,

I am developing an eCommerce site and I have a question related to the cart. Currently I have a Cart model and a CartItem model where the cart and its content is stored. When a user adds a product to cart, I create the cart and store the cart ID in session.

My problem is when the user logs out the session is cleared and the user gets an empty cart because the cart ID in session is no longer there.

What is the best way to solve this issue?

0 likes
3 replies
mushood's avatar

The cart should be related to the user. When the user logs in again, fetch his cart and set the cart ID to the session again.

Also the user can have a remember_me token in the login page, if he checks this box, when he comes back to the site, he will automatically login again. Then you can fetch his cart when he comes back.

Alternatively, you could set a cookie with the cart id which will stay longer even if the user closes the browser. However, what happens if he clears his cookie?

chatty's avatar

@eriktobben

$cart = session()->pull('cart');
auth()->logout();
session()->put(['cart' => $cart]);

I don't know your code, but this should give you an idea

elham's avatar

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

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('/');

}

2 likes

Please or to participate in this conversation.