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

Laravel报错:Collection::exists方法不存在,求解决商品单次下单逻辑

问题解决:Method Illuminate\Database\Eloquent\Collection::exists does not exist

报错原因

auth()->user()->orders返回的是Eloquent集合(Collection),而exists()是查询构造器(QueryBuilder)的专属方法,集合类没有这个方法,因此触发报错。此外你还存在两处逻辑错误:一是匹配字段错误(要判断用户是否下单过当前商品,应该匹配product_id而非user_id);二是判断逻辑和需求完全相反(原代码是存在订单才显示按钮,需求是存在订单就隐藏按钮)。

修正方案

  1. 将关联集合调用改为关联查询构造器调用:给orders添加括号orders(),返回QueryBuilder实例,即可正常使用exists()方法。
  2. 修正字段匹配:把where('user_id', $product->id)改为where('product_id', $product->id),匹配商品ID。
  3. 反转判断逻辑:用@unless或@if(!...)实现「用户未下单过该商品时才显示按钮」的需求。

修正后的视图代码

@unless(auth()->user()->orders()->where('product_id', $product->id)->exists())
    @if(App\Services\Cart\Cart::count($product) < $product->inventory)
        <form action="{{ route('add.to.cart', $product->id) }}" method="post" id="add-to-cart">
            @csrf
        </form>
        <span onclick="document.getElementById('add-to-cart').submit()" class="cursor-pointer btn btn-lg bg-navy-blue text-white">
            <span>Order</span>
        </span>
    @endif
@endunless

也可以用@if写法:

@if(!auth()->user()->orders()->where('product_id', $product->id)->exists())
    @if(App\Services\Cart\Cart::count($product) < $product->inventory)
        <form action="{{ route('add.to.cart', $product->id) }}" method="post" id="add-to-cart">
            @csrf
        </form>
        <span onclick="document.getElementById('add-to-cart').submit()" class="cursor-pointer btn btn-lg bg-navy-blue text-white">
            <span>Order</span>
        </span>
    @endif
@endif

补充说明

如果坚持用集合操作(不推荐,会加载用户所有订单到内存,性能较差),可以把exists()换成集合的isNotEmpty(),同时修正字段匹配:

@if(!auth()->user()->orders->where('product_id', $product->id)->isNotEmpty())
    <!-- 按钮代码 -->
@endif

优先推荐查询构造器的方式,只会执行一条EXISTS查询,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:32:56