skip to Main Content

I’m using this package "darryldecode/cart" for shopping cart functionality in laravel,
for adding items to cart using this method

  Cart::session($userID)->add([
            'id' => $productId,
            'name' => $productDetails['name'],
            'price' => $productDetails['price'],
            'quantity' => $productDetails['quantity'],
            'attributes' => [],
            'associatedModel' => $productDetails,
        ]);

but i have doubt if user is not logged in then how we are going to add the items to cart and after user is logged then associate the product with logged in user Id.

Any solution Thanks

2

Answers


  1. you can use a temp user make a cookie with the user token to assign the cart to him and if he login remove the user and reassign to the actual user

    Login or Signup to reply.
  2. I believe if you associate that guest client with a session id, you can later get that guest client session id and associate with the newly logged session id

    an example for that:

    // Generating a unique identifier for a guest user
    $guestSessionId = session()->get('guestSessionId', function() {
       return session()->put('guestSessionId', uniqid('guest_', true));
    });
    
    // Adding item to cart for a guest user
    Cart::session($guestSessionId)->add([
        'id' => $productId,
        'name' => $productDetails['name'],
        'price' => $productDetails['price'],
        'quantity' => $productDetails['quantity'],
        'attributes' => [],
        'associatedModel' => $productDetails,
    ]);
    

    Then you need to handle those sessions and assosiate them with an account

    public function loginUser(Request $request)
    {
        // here your current auth login, or create one...
    
        $userId = auth()->id(); // or however you get the logged-in user's ID
        $guestSessionId = session('guestSessionId');
    
        // Check if there is a cart for the guest user
        if (Cart::session($guestSessionId)->getContent()->isNotEmpty()) {
            // Merge guest cart into user cart
            $guestCartItems = Cart::session($guestSessionId)->getContent();
            foreach ($guestCartItems as $item) {
                Cart::session($userId)->add($item);
            }
    
            // Clear the guest cart
            Cart::session($guestSessionId)->clear();
    
            // Remove the guestSessionId as it's no longer needed
        session()->forget('guestSessionId');
        }
        // everything else of the login logic...
    }
    

    I believe this can work in your project, If anything just ask and i’ll adapt the response to your actual code.

    cheers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search