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

Laravel购物车报错Trying to access array offset on value of null

问题现象

点击购物车按钮时Laravel框架抛出错误:
Trying to access array offset on value of type null

错误栈信息:

Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\xampp\htdocs\laravel-ecommerce\app\Listeners\CartUpdatedListener.php:30 

异常由框架内置异常处理器捕获,出错位置为项目路径下app/Listeners/CartUpdatedListener.php文件第30行,对应handle方法原始代码:

public function handle($event)
    {
        $couponName = session()->get('coupon')['name'];
        if ($couponName) {
            $coupon = Coupon::where('code', $couponName)->first();
            dispatch_now(new UpdateCoupon($coupon));
        }
    }
报错原因

代码直接读取session中coupon项的name下标,未做前置判空处理。当session里不存在coupon键时,session()->get('coupon')默认返回null,对null值读取数组下标就会触发该类型错误。

修复方案

使用空合并运算符做安全取值,同时补充优惠券模型的存在性判断,避免后续传null值到任务类触发二次报错,修复后代码:

public function handle($event)
    {
        // 安全读取session中的优惠券名称,不存在时默认赋值null
        $couponName = session()->get('coupon')['name'] ?? null;
        if ($couponName) {
            $coupon = Coupon::where('code', $couponName)->first();
            // 确认优惠券记录存在再分发任务
            if ($coupon) {
                dispatch_now(new UpdateCoupon($coupon));
            }
        }
    }

如果需要做更严格的类型校验,也可以使用以下写法:

public function handle($event)
    {
        $couponSession = session()->get('coupon');
        $couponName = is_array($couponSession) && array_key_exists('name', $couponSession) 
            ? $couponSession['name'] 
            : null;
        
        if ($couponName) {
            $coupon = Coupon::where('code', $couponName)->first();
            if ($coupon) {
                dispatch_now(new UpdateCoupon($coupon));
            }
        }
    }

内容的提问来源于stack exchange,提问作者Zin Myo Swe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 22:39:25