John
John

Reputation: 61

Flushing all session variables while keeping user logged in - Laravel 5

How could I keep a user logged in when trying to destroy a cart session when they complete an order?

I am trying to flush a cart session whenever a user completes an order on my site, when the order is complete the user is redirected but the items in their cart are still there, is there anyway to delete them and keep the user logged in?

I store my session like so

$cart = session()->get('cart');

        // if cart is empty then this will be the first product
        if (!$cart) {


            $cart = [
                $id => [
                    "id" => $product->id,
                    "name" => $product->name,
                    "quantity" => 1,
                    "price" => $product->unit_price
                ]
            ];

            session()->put('cart', $cart);

            return redirect()->back()->with('success', 'Product added to cart successfully!');
        }

And trying to delete it like so

$cart = session()->get('cart');


            if (isset($cart[$request->id])) {

                unset($cart[$request->id]);

                session()->put('cart', $cart);
            }

            session()->flash('success', 'Order Fulfilled');


        return redirect("/");

Upvotes: 1

Views: 763

Answers (2)

John
John

Reputation: 61

When I update my refresh function to this below, the session restarts

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

        $cart = session()->get('cart');

        if (!$cart) {
            session()->put('cart', []);
        }

        return redirect("/");

Upvotes: 2

Ashish
Ashish

Reputation: 6919

If your using $request->session()->flush(); then it will flush or destroy your whole data.

Try to use $request->session()->forget('key');. Just pass the Key in Forget Method. Which will remove only Session data belongs to that Key.

Upvotes: 1

Related Questions