You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8 array_key_exists()参数2为null报错如何解决?

修复方案

问题根因

你传入构造函数的$cart实例的items属性本身为null,原构造函数仅在$cart为空的场景下为$this->items初始化空数组,传入$cart时直接赋值未做合法性校验,导致后续调用array_key_exists()时第二个参数不符合数组要求。

修复步骤

  1. 改造构造函数,兜底保证$this->items始终为数组类型
public function __construct($cart = null)
{
    // 先初始化默认值
    $this->items = [];
    $this->totalQty = 0;
    $this->totalPrice = 0;

    if ($cart) {
        // 仅当传入的cart->items为数组时才覆盖,否则保留默认空数组
        $this->items = is_array($cart->items) ? $cart->items : [];
        $this->totalPrice = $cart->totalPrice ?? 0;
        $this->totalQty = $cart->totalQty ?? 0;
    }
}
  1. 优化add方法,增加前置校验避免异常,同时简化重复逻辑
    可以直接使用Laravel自带的Arr::has辅助方法,该方法会自动判断目标是否为数组,无需额外手动校验:
use Illuminate\Support\Arr;

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

    if (!Arr::has($this->items, $product->id)) {
        $this->items[$product->id] = $item;
    }
    
    // 公共逻辑统一执行,无需重复写两次
    $this->totalQty += 1;
    $this->totalPrice += $product->price;
    $this->items[$product->id]['qty'] += 1;
}

如果不想引入Arr门面,也可以直接在判断前加数组校验:

if (!is_array($this->items) || !array_key_exists($product->id, $this->items))

内容的提问来源于stack exchange,提问作者ToddM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 01:12:01