I have a model called Products, and I need to return the related products to the view. So I created another model called Category, and the relation is many-to-many.
I managed to get the related products but each with a category attached to it which is not quit good, and this my code:
$categories = Product::find($id)->categories;
$products = new Product;
$products = $products->toArray();
foreach ($categories as $cat) {
array_push($products, Category::find($cat->id)->products);
}
return $products;
Is there a better way to do that ?
I did it using regular SQL query and here is the code hoping for helping someone
$catIDs = DB::table('product_category')
->select('category_id')
->where('product_id', $id)
->pluck('category_id');
$productsIDs = DB::table('products')
->select('product_category.product_id')
->distinct()
->rightJoin('product_category', 'products.id', '=', 'product_category.product_id')
->whereIn('category_id', $catIDs)
->pluck('product_id');
$relatedProducts = Product::with('firstImage')
->whereIn('id', $productsIDs)
->where('id', '!=', $id)
->inRandomOrder()
->get();