Search code examples
phplaravelsessionshopping-cart

Clearing shopping cart after checkout


I have implemented a shopping cart in laravel using sessions. Now, i think I am kinda unclear as to how I would clear the cart for each user after checkout. My understanding is that sessions are created when the browser is open and destroyed when it is closed. I also get that sessions are created on the users machine. How would i go about destroying that session object after user has checked out?

What, i have is that, a status code would be sent back to a route in my application that would trigger the clear cart function if the payment was successful. Have i misunderstood how sessions operate?

I expect that when a user completes a transaction, the payment gateway will return a code and i could use that code to clear session.


Solution

  • Yes, you can clear the session value for cart on successful transaction.

    Assuming you store your cart details in session in a key called cart, you can delete it from session like this:

    $request->session()->forget('cart'); 
    

    or using the helper method like this:

    session()->forget('cart');
    

    This is if the cart details are stored in session, if they are stored in your db, you can begin a mysql (given you are using mysql) transaction at the beginning of your checkout and clear the cart for that particular user. In case of a payment failure, you can rollback the transaction leaving everything intact in cart.