I have ShopController . Now I am displaying products in random order from database. Here is the code
$productsLike = Product::with('categories')->where('slug', '!=', $slug)->inRandomOrder()->take(4)->get();
What i should do to display products related to the same category as current product?
CodePudding user response:
You can check with category id.
$productsLike = Product::with('categories')
->where('category_id_column', $category_id)
->where('slug', '!=', $slug)
->inRandomOrder()->take(4)->get();
CodePudding user response:
I would make a local scope
on your Product
model to make things reusable.
public function scopeRelatedProducts($query, $count = 10, $inRandomOrder = true)
{
$query = $query->where('category_id', $this->category_id)
->where('slug' '!=' $this->slug);
if ($inRandomOrder) {
$query->inRandomOrder();
}
return $query->take($count);
}
Then you could do something like:
$related = Product::relatedProducts(4, true)->with('categories')->get();
This assumes the column your Product
table stores the relationship to a Category
follows the Laravel naming convention (e.g. RelatedModelName_id
).
You could also replace the slug_id
with the Product
id
You can then use the resulting $related
variable in your view, so assuming your using the above in a Product
show
controller method, you might do:
class ProductController
{
public function show (Product $product)
{
$related = $product->relatedProducts(4, true)->with('categories')->get();
return view('products.show', compact('product', 'related');
}
}
@foreach ($related as $item)
<h5>{{ $item->name }}</h5>
<p>{{ $item->description }}</p>
@endforeach