Laravel中如何获取排除当前商品的10个随机商品列表?
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

