mafortis
mafortis

Reputation: 7128

Show products in laravel cart

I have laravel 5.5 project and I made cart system with session, As I debug it, it works fine and adds products to cart but to getting products with foreach in cart view I have issue, here is the error:

Invalid argument supplied for foreach()

This is my blade code:

@if (Session::has('cart'))
    @foreach($products as $product)
        {{$product->title}}
    @endforeach
@else
    no product
@endif

Here is my Cart model

public $items;
public $totalQty = 0;
public $totalPrice = 0;

public function __construct($oldCart) {
   if ($oldCart) {
        $this->items = $oldCart->items;
        $this->items = $oldCart->totalQty;
        $this->items = $oldCart->totalPrice;
   }
}

public function add($item, $id) {
   $storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
   if ($this->item) {
        if (array_key_exists($id, $this->items)) {
          $storedItem = $this->items[$id];
        }
   }
   $storedItem['qty']++;
   $storedItem['price'] = $item->price * $storedItem['qty'];
   $this->items[$id] = $storedItem;
   $this->totalQty++;
   $this->totalPrice += $item->price;
}

And this is my CartController

public function AddToCart(Request $request, $id)
{
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->add($product, $product->id);
        $request->session()->put('cart', $cart);
        return redirect()->back();
}

public function index()
{
      if (!Session::has('cart')) {
        return view('frontend.cart');
      }
      $oldCart = Session::get('cart');
      $cart = new Cart($oldCart);
      return view('frontend.cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
}

This is my route:

//Cart
Route::resource('/cart', 'CartController', ['except' => ['show', 'create']]);

// Session route for add to cart
Route::get('/add-to-cart/{id}', [
  'uses' => 'CartController@AddToCart',
  'as' => 'product.addToCart'
]);

Anyone knows what the issue with my blade loop?

Upvotes: 0

Views: 770

Answers (1)

CUGreen
CUGreen

Reputation: 3186

It would appear that the error is here:

public function __construct($oldCart) {
  if ($oldCart) {
    $this->items = $oldCart->items;
    $this->items = $oldCart->totalQty;
    $this->items = $oldCart->totalPrice;
  }
}

it looks like $this->items = $oldCart->totalPrice; is a float value rather than an array.

Perhaps it should be:

public function __construct($oldCart) {
  if ($oldCart) {
    $this->items = $oldCart->items;
    $this->totalQty = $oldCart->totalQty;
    $this->totalPrice = $oldCart->totalPrice;
  }
}

Upvotes: 0

Related Questions