0
votes

i tried adding to cart an i keep getting this error Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given, called in C:\xampp\htdocs\laravelcart\app\Http\Controllers\ProductController.php

here is my code

cart.php model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cart extends Model
{
    //

    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;
    }
}



product controller
<?php

namespace App\Http\Controllers;

use App\Product;
use Session;
use App\Cart;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    //

    public function getIndex()
    {
        $products = Product::all();
        return view('shop.index', compact('products'));
    }

    public function getAddToCart(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()->route('shop.index');

    }
}

my error seems to be coming from the $cart = new Cart($oldCart); pls help me...

1

1 Answers

0
votes

The problem here is your constructor. In fact you don't call "constructor" that you defined but parent constructor is executed. This is because you miss one underscore, it should be __construct.

However it's not good idea to do it like this. First of all, you should call parent constructor, and in addition such custom constructor can cause problems in some scenarios.

It's much better to add method like this:

public static function restoreCart($oldCart)
{
    $cart = new static();

    if ($oldCart) {
        $cart->items = $oldCart->items;
        $cart->totalQty= $oldCart->totalQty;
        $cart->totalPrice = $oldCart->totalPrice;
    }

    return $cart;
}

and then in your controller instead of:

$cart = new Cart($oldCart);

you can use:

$cart = Cart::restoreCart($oldCart);