stefancoding's avatar

How to access Cart Collection

hi guys. I just installed the bumbummen99/shoppingcart package. But I cant access the "image".

Illuminate\Support\Collection {#423 ▼
  #items: array:1 [▼
    "155ef990fda59c10390f3fe6c4d6e734" => Gloudemans\Shoppingcart\CartItem {#424 ▼
      +rowId: "155ef990fda59c10390f3fe6c4d6e734"
      +id: 764838
      +qty: 2
      +name: "ROYAL ENFIELD MUSTANG "
      +price: 18.33
      +weight: 0.0
      +options: Gloudemans\Shoppingcart\CartItemOptions {#425 ▼
        #items: array:1 [▼
          "image" => "85-600x600.jpg"
        ]
        #escapeWhenCastingToString: false
      }
      +taxRate: 21
      -associatedModel: null
      -discountRate: 0
      +instance: "default"
    }
  ]

I could access the id, name, price but I dont know how to get the "image".

0 likes
8 replies
kokoshneta's avatar

You access it like any other member of any other collection, I presume:

foreach ($cart->options as $option) {
	$image = $option['image'];
}

Does that not work?

kokoshneta's avatar

@stefancoding No, of course it doesn’t – that was just me being stupid. I’m used to dealing with collections of objects, and my brain frazzled. What I should have written was:

$image = $cartItem->options->get('image');
kokoshneta's avatar

@stefancoding Then your cartItem’s $options property is a string, not a CartItemOptions collection.

I’m guessing the output in your question is from doing dd(Cart::content()), right? Try showing us what this gets you:

foreach (Cart::content() as $item) {
	dd($item->options);
}
kokoshneta's avatar

@Rumnaz khan That’s exactly the same as I wrote (->image does the same as ->get('image') in the CartItemOptions class), which didn’t work, for some reason.

stefancoding's avatar

Is working now.. The problem was that I looped twice. I looped over the Cart then I tried to loop overt the Options array.

@foreach($carts as $product)
		@foreach($product->options as $option)
				$option // this showing me only the image from options but not showing other options
				$option['image'] // this not working
	@endforeach
@endforeach

So I did with only one for each and its works now

@foreach($carts as $product)
	$product->options['image']
	$product->options['mainId']
	$product->options['size']
@endforeach

Please or to participate in this conversation.