my project has main category - sub category and products. each product has a subcategory_id and each subcategory has a category_id.
now the problem is how to select and show products related to main category. by relations I am getting subcategory products like $subcat->Product, or main category's subcategories like $cat->Subcateogry, but I have no idea how to get products for main category.
for clearing it more:
category (digital goods)
--subcategory (laptop , mobile , tv)
----product (l1 , l2 , m1 , m2 , t1 , t2)
in laptop subcategory view we have l1 and l2 but how is it possible to show them in main category (digital goods).
if your relation setup correctly you could do it using :
$allProductInMainCategory=MainCategory::where('id',$mainCategoryId)->
with('subCategories.products')->get();
another option is to use nested whereHas
$allProductInMainCategory=Product::whereHas('subCategory',function($query)use($mainCategoryId){
$query->whereHas('mainCategory',function($q)use($mainCategoryId)
{
$q->where('mainCategories.id',$mainCategoryId);
});
})->get();