Typed property App\Models\Product::$id must not be accessed before initialization

Viewed 27

The following error is related to the card model part of a store site project that I am programming with Laravel 9.2 and I could not solve the error.

enter image description here

Cart.php

namespace App\Models;
use App\Models\Product;
use App\Models\Order;

class Cart
{
    public $products = [];
    public $count = 0;
    public $price = 0;
    public $address = null;

    public function __construct($Cart = null)
    {
        if (!is_null($Cart)) {
            $this->products = $Cart->products;
            $this->count = $Cart->count;
            $this->price = $Cart->price;
            $this->address = $Cart->address;
        }
    }

    public function addToCart($products)
    {
        if (array_key_exists($products->id , $this->products)) {
            $this->products[$products->id] = [
                "products" => $products,
                "count" => $this->products[$products->id]['count'] + 1,
            ];
        } else {
            $this->products[$products->id] = [
                "products" => $products,
                "count" => 1,
            ];
        }
        $this->price += $products->price;
        $this->count += 1;
    }

UPDATE

OrderController.php

 <?php
        
        namespace App\Http\Controllers\Site;
        
        use App\Models\Cart`;`
        use App\Models\Product;
        use App\Http\Controllers\Controller;
        use Illuminate\Http\Request;
        
        class OrderController extends Controller
        {
            public function addToCart(Product $product, Request $request)
            {
                $oldCart = $request->session()->has("cart") ? $request->session()->get("cart") : null;
            $cart = new Cart($oldCart);
            $cart->addToCart($product);
            $request->session()->put("cart", $cart);
        }
        public function cartshow(Request $request)
        {
            $oldCart = $request->session()->has("cart") ? $request->session()->get("cart") : null;
            $cart = new Cart($oldCart);
            dd($cart);
        }
    }
0 Answers
Related