Reuqirment
My DB has a table named categories and also a table named products where products table has a row named category_id which make the relationship with categories table. So I wants to show random 7 categories from my categories table and also I needs to show 6 products from each category too.
Framework
Laravel 5.3
What I have done
To fetch 8 random categories
This code work as I wants so no issue with this code segment
$masterCategoryList = Category::where('parent_id', 0) ->where('id', '!=',0) ->inRandomOrder() ->take(8) ->get();Fetch 6 random products for each selected random Master Category List id
$masterCategoryListSo what I have done is$productsMatcheToMasterCategory = []; for($a = 0; $a<8; $a++){ $productsMatcheToMasterCategory = Product::where('category_id',$masterCategoryList[$a]['id']) ->inRandomOrder() ->take(6) ->get(); }
But this only output 6 products which related one category when I use dd($productsMatcheToMasterCategory)after the loop.Like below
Category 01
- Product 01
- Product 02
My expected out put is something like below
Category 01
- Product 01
- Product 02
Category 02
- Product 01
- Product 02
Could anyone please tell me why does this happen.
Thanks