Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Illegal offset type in isset or empty

How to add to cart? When I want add to cart I see this error

    public function addToCart(Product $product)
    {
        $cart = session()->get('cart', []);
        if (Cart::has($product)) {
            if(Cart::count($product) < $product->inventory)
                Cart::update($product, 1);
        } else {
            if(isset($cart[$product])) {
                $cart[$product]['quantity']++;
            } else {
                $cart[$product] = [
                    "title" => $product->title,
                    "quantity" => 1,
                    "image" => $product->image,
                    "price" => $product->price,
                ];
                Cart::put(
                    [
                        'quantity' => 1,
                    ],
                    $product
                );
            }
        }
        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }

error

0 likes
8 replies
Sinnbeck's avatar

$product is an object. You cannot use it as an array key

$cart[$product]
//maybe you meant to do this?
$cart[$product->id]
Sinnbeck's avatar

What is your code is meant to do? Are you using a package?

Sinnbeck's avatar

@waves don't use an object as key in an array. I already have shown an example

shahr's avatar
Level 10

@Sinnbeck I get this error again

Illegal offset type.

This error occurred on this line.

$cart[$product] = [
Sinnbeck's avatar

@waves Yes. You cannot use an object as key. I think I said so earlier?

For instance you can do

$cart[$product->id] = [

Please or to participate in this conversation.