Laravelshoppingcart: Store in DB

Created on 17 Oct 2017  路  5Comments  路  Source: Crinsane/LaravelShoppingcart

Hello! Thank you for this package, it is very usefull.

In my project I want to do this. "User One" logges in, put several items to the cart and loggs out. After a while he logges in again and sees items in his cart. I know than I may use store method, but I don't understand how, cause I have a "CartAlreadyStoredException". Where may I put code for this method?

My code for _adding products_:

public function addProductToCart(Request $request, $id)
    {
        if ($request->has('amount')){
            $amount = $request->amount;
        } else {
            $amount = 1;
        }

        $product = Product::find($id);

        Cart::instance('shopping')->add($id, $product->name, $amount, $product->price);

        if(Auth::check()){
            Cart::instance('shopping')->store(Auth::user()->id); //error!
        }

        return back();
    }

and for _displaying_: (now it shows items that are in the session, but I want to swith between cart in the session for not auth users and between cart in the DB for auth users)

public function cart()
    {
        $cartItems = Cart::instance('shopping')->content();

        return view ('orders.cart', compact('cartItems'));
    }

To sum up, _I need to use session when user is guest in and DB when user is logged in._

Once again, thanks for package. I hope someone can help me:)

All 5 comments

I'm afraid you're using the 'store' method in another way than it's designed for. The idea is that you can 'store' the cart for a later point in time, and 'restore' it when the user wants it again.

It's not really designed to store the cart in the database 'realtime' so to say.

Thanks for your answer)
If someone has this problem, that's my suggestion. In logout method:

public function logout(Request $request)
    {
        Cart::instance('shopping')->restore(Auth::user()->id);
        Cart::instance('shopping')->store(Auth::user()->id);
        $this->guard()->logout();
        $request->session()->invalidate();
        return redirect('...');
    }

i'm logout but my data is 0, how to keep the data there if i'm login again?

@humamalamin
If I am logged in I store data in the session.
My updated logout function

public function logout(Request $request)
    {
       //delete old cartitems
        DB::table('shoppingcart')->where([
                ['identifier', Auth::user()->id],
                ['instance', 'shopping']
            ])->delete();

        DB::table('shoppingcart')->where([
            ['identifier', Auth::user()->id],
            ['instance', 'wishlist']
        ])->delete();

        //save new cart items
        Cart::instance('shopping')->store(Auth::user()->id);
        Cart::instance('wishlist')->store(Auth::user()->id);

        $this->guard()->logout();
        $request->session()->invalidate(); //clear session data. cart became empty
        return redirect(something_url); 
    }

When I'm logged in I combine data from DB (if it is exists) and data from the cart (if customer add smth already)

    public function login(Request $request)
    {
        /*
         * .....
         * checking validation and logging user in. if OK
         */

        // get cart from DB if it exists
        $storedCartItems = DB::table('shoppingcart')->where([
            ['identifier', Auth::user()->id],
            ['instance', 'shopping']
        ])->value('content');

        // get wishlist from DB if it exists
        $storedWishlistItems = DB::table('shoppingcart')->where([
            ['identifier', Auth::user()->id],
            ['instance', 'wishlist']
        ])->value('content');

        $storedCartItems = \unserialize($storedCartItems);

        $storedWishlistItems = \unserialize($storedWishlistItems);

        // check if count of each product in the store is more than in the cart and more than 0 (only for cart)
        if($storedCartItems){
            foreach ($storedCartItems as $item){
                Cart::instance('shopping')->add($item->id, $item->name, $item->qty, $item->price)->associate('App\Product');
                // if it passes, I'll add them to the cart in the session
                if (($item->model->qty > 0) & ($item->model->qty < $item->qty)){
                    Cart::instance('shopping')->update($item->rowId, $item->model->qty);
                // if it does not pass, I will not add them to the cart in the session
                } elseif ($item->model->qty == 0){
                    Cart::instance('shopping')->remove($item->rowId);
                }
            }
        }

        //add items from wishlist from DB to the wishlist items in the session
        if($storedWishlistItems){
            foreach ($storedWishlistItems as $item){
                Cart::instance('wishlist')->add($item->id, $item->name, $item->qty, $item->price)->associate('App\Product');
            }
        }

     // return redirect or smth else
    }

That works for me. Hope it can help you)

thansk, i try it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hatamiarash7 picture hatamiarash7  路  6Comments

matbeard picture matbeard  路  7Comments

pelachile picture pelachile  路  8Comments

nareshbabu557 picture nareshbabu557  路  8Comments

nasirkhan picture nasirkhan  路  8Comments