user8705895
user8705895

Reputation:

Laravel errors: call to undefined method App\Cart::items()

I am developing a shopping cart project in Laravel 6.1. When I click the add button, the values were increased by one, but when I click the same button twice I am getting the following error:

Symfony\Component\Debug\Exception\FatalThrowableError Call to undefined method App\Cart::items() http://localhost:8000/add-to-cart/3

Cart.php

class Cart
{
    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;

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

    public function add($item, $id)
    {
        $storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];

        if ($this->items) {
            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;
    }
}

Controller

class ProductController extends Controller
{
    public function getIndex()
    {
        $products = Product::all();

        return view('shop.index', ['products' => $products]);
    }

    public function getAddToCart(Request $request, $id)
    {
        $product = Product::find($id);
        $cart = Session::has('cart') ? Session::get('cart') : null;
        if (!$cart) {
            $cart = new Cart($cart);
        }
        $cart->add($product, $product->id);
        Session::put('cart', $cart);

        return redirect()->route('product.index');
    }

    public function getCart()
    {
        if (!Session:: has('cart')) {
            return view('shop.shopping-cart', ['products' => null]);
        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);

        return view('shop.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
    }
}

Screenshot of error

el

Upvotes: 0

Views: 1838

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

You are using function call instead of property.

You should change:

$storedItem =$this->items($id);

into

$storedItem = $this->items[$id];

to access element with given $id

Upvotes: 1

Related Questions