sunilbfcj
6 days ago

Laravel Session::get('key') always returns null

Posted 6 days ago by sunilbfcj

I am adding product in cart using session but when I refresh page session return null for the key.

$product = Product::where('slug', $request->slug)->where('status', 'published')->first();

$cart = Session::has('cartdata') ? json_decode(Session::get('cartdata')) : [];
          //dd($cart);
          if(!isset($cart[$product->id])){
            $cart[$product->id][] = [
              'attributes' => $product->type=='variable' ? json_encode($request->attribute) : null,
              'quantity' => $request->quantity,
              'cart_type' => $request->addToWishlist ? 'wishlist' : 'cart'
            ];
          }
          else{
            $found = 1;
            $attribute = $product->type=='variable' ? json_encode($request->attribute) : null;
            foreach($cart[$product->id] as $key => $val){
              //echo $cart[$product->id][$key]['attributes'].' / '.$attribute;
              if($cart[$product->id][$key]['attributes']==$attribute){
                $cart[$product->id][$key]['quantity'] = $request->quantity;
                $cart[$product->id][$key]['cart_type'] = $request->addToWishlist ? 'wishlist' : 'cart';
                $found = 0;
              }
            }
            if($found){
              $cart[$product->id][] = [
                'attributes' => $product->type=='variable' ? json_encode($request->attribute) : null,
                'quantity' => $request->quantity,
                'cart_type' => $request->addToWishlist ? 'wishlist' : 'cart'
              ];
            }
          }
          if(count($cart)){
            $request->session()->put('cartdata', json_encode($cart));
          }
          dd($cart);

Please sign in or create an account to participate in this conversation.