传递给Illuminate \ Database \ Eloquent \ Model :: __ construct()的参数1必须是数组类型,给定的对象,

时间:2018-09-28 03:15:06

标签: php laravel laravel-5 eloquent laravel-5.7

我尝试将其添加到购物车,但我不断收到此错误 传递给Illuminate \ Database \ Eloquent \ Model :: __ construct()的参数1必须是给定对象的数组类型,在C:\ xampp \ htdocs \ laravelcart \ app \ Http \ Controllers \ ProductController.php

中调用

这是我的代码

cart.php模型

<?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');

    }
}

我的错误似乎来自 $ cart =新手推车($ oldCart); 请帮助我...

1 个答案:

答案 0 :(得分:0)

这里的问题是您的构造函数。实际上,您不会调用您定义的“构造函数”,而是会执行父构造函数。这是因为您错过了一个下划线,应该是__construct

但是,这样做不是一个好主意。首先,您应该调用父构造函数,此外,这种自定义构造函数还会在某些情况下引起问题。

最好添加这样的方法:

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

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

    return $cart;
}

,然后在您的控制器中,而不是:

$cart = new Cart($oldCart);

您可以使用:

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