Laravel报错:Collection::exists方法不存在,求解决商品单次下单逻辑
问题解决:Method Illuminate\Database\Eloquent\Collection::exists does not exist
报错原因
auth()->user()->orders返回的是Eloquent集合(Collection),而exists()是查询构造器(QueryBuilder)的专属方法,集合类没有这个方法,因此触发报错。此外你还存在两处逻辑错误:一是匹配字段错误(要判断用户是否下单过当前商品,应该匹配product_id而非user_id);二是判断逻辑和需求完全相反(原代码是存在订单才显示按钮,需求是存在订单就隐藏按钮)。
修正方案
- 将关联集合调用改为关联查询构造器调用:给
orders添加括号orders(),返回QueryBuilder实例,即可正常使用exists()方法。 - 修正字段匹配:把
where('user_id', $product->id)改为where('product_id', $product->id),匹配商品ID。 - 反转判断逻辑:用
@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
相关产品推荐
相关产品推荐

