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

Laravel中如何获取排除当前商品的10个随机商品列表?

Fix: Exclude Current Product from Random Recommendations

Got it, let's sort this out quickly! The problem is your current random product query isn't excluding the item the user is already viewing. Here's how to adjust your code to guarantee those 10 random products are 100% distinct from the current page's product:

First, keep your existing code for fetching the current product—no changes needed there:

$product = Product::where('slug', $slug)->firstOrFail();

Now modify your random product query to exclude the current product's ID using a where clause:

$random = Product::where('id', '!=', $product->id)
    ->inRandomOrder()
    ->limit(10)
    ->get();

How this works:

  • The where('id', '!=', $product->id) condition filters out any product with the same ID as the one on the current page.
  • inRandomOrder() still handles shuffling the remaining products.
  • limit(10) ensures you get up to 10 results (if there are fewer than 10 other products in your database, it'll just return all available ones—no errors here).

If you prefer a slightly more explicit syntax (useful if you ever need to exclude multiple IDs later), you can use whereNotIn instead:

$random = Product::whereNotIn('id', [$product->id])
    ->inRandomOrder()
    ->limit(10)
    ->get();

Either approach will solve your issue and keep the random section free of the current product.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:30:03