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

Laravel加购成功但购物车不显示,报Trying to get property 'image' of non-object错误

错误原因分析

报错Trying to get property 'image' of non-object的核心原因是你代码中调用的$item->model为null,没有返回对应的商品模型对象,触发这个问题的常见场景如下:

  • 加购商品时未正确关联商品模型:你使用的Laravel购物车扩展在添加商品时需要手动关联对应模型,未执行关联操作的话$item->model会始终为null
  • 对应商品已被删除:购物车仅存储商品ID,若后台已经删除了该商品条目,读取购物车时就无法关联到对应模型
  • 购物车配置错误:config/cart.php中配置的默认模型命名空间与你实际使用的商品模型路径不匹配
临时修复方案

你可以先在blade模板中增加模型存在性判断,先让购物车页面可以正常加载,同时给用户提示无效商品:

@foreach(Cart::instance('cart')->content() as $item)
    @if($item->model)
    <li class="pr-cart-item">
        <div class="product-image">
            <figure><img src="{{asset('assets/images/products')}}/{{$item->model->image}}" alt="{{$item->model->name}}"></figure>
        </div>
        <div class="product-name">
            <a class="link-to-product" href="{{route('product.details',['slug'=>$item->model->slug])}}">{{$item->model->name}}</a>
        </div>
        <div class="price-field produtc-price"><p class="price">${{$item->model->regular_price}}</p></div>
        <div class="quantity">
            <div class="quantity-input">
                <input type="text" name="product-quatity" value="{{$item->qty}}" data-max="120" pattern="[0-9]*" >                                  
                
                <a class="btn btn-increase" href="#" wire:click.prevent="increaseQuantity('{{$item->rowId}}')"></a>
                <a class="btn btn-reduce" href="#" wire:click.prevent="decreaseQuantity('{{$item->rowId}}')"></a>
            </div>

            <p class="text-center"> <a href="#" wire:click.prevent="switchToSaveForLater('{{$item->rowId}}')">Save For Later</a></p>
        </div>
        <div class="price-field sub-total"><p class="price">${{$item->subtotal}}</p></div>
        <div class="delete">
            <a href="#" wire:click.prevent="destroy('{{$item->rowId}}')" class="btn btn-delete" title="">
                <span>Delete from your cart</span>
                <i class="fa fa-times-circle" aria-hidden="true"></i>
            </a>
        </div>
    </li>
    @else
    <li class="pr-cart-item">
        <p>该商品已下架或不存在,<a href="#" wire:click.prevent="destroy('{{$item->rowId}}')">点击删除</a></p>
    </li>
    @endif
@endforeach

如果你的服务端PHP版本在7.4以上,也可以用null安全运算符简化写法,无需额外判断:
把所有$item->model->xxx替换为$item->model?->xxx即可,访问不存在的属性时会直接返回null而不会抛出错误。

根因修复方法
  1. 检查加购逻辑代码,确保添加商品时调用了associate方法关联商品模型,示例代码如下:
// 请将App\Models\Product替换为你实际的商品模型路径
$product = Product::findOrFail($productId);
Cart::instance('cart')
    ->add($product->id, $product->name, $buyNum, $product->regular_price)
    ->associate('App\Models\Product');
  1. 检查config/cart.php配置文件,确认默认模型的命名空间配置和你实际的商品模型路径一致。
  2. 新增定时任务定期清理购物车中的无效条目,避免已删除商品长期滞留在用户购物车中引发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:30:00