S.I.
S.I.

Reputation: 3375

Query to load sub categories or products

I'm trying to make it when user click on main category on next page to load all subcategories BUT if there is no subcategories assigned to this main category to show all products which are assigned to main category.

What I tried so far is this: My Controller:

public function showSubCats($categoryId) {
     $ifNoSubCategory = Categories::with('products')->get();             
     $subcats = SubCategories::where('category_id', '=', $categoryId)->get();
     return View::make('site.subcategory', [            
          'subcats' => $subcats,
          'ifNoSubCategory' => $ifNoSubCategory
     ]); 
}

Here is the view

@if(count($subcats) > 0)
  @foreach($subcats as $i => $subcategory)

      // looping sub categories assigned to main category

  @endforeach
@else
   @foreach($ifNoSubCategory as $i => $singles)

      // looping products assigned to main category

   @endforeach
@endif

What is happening is if there are subcategories they are shown properly on page but if there is not subcategories it is showing the box of the product but doesn't load product name, image, price etc.. just empty html structure..

When I dd($ifNoSubCategory) It is showing me proper data which must be on the page..

Where is my mistake here?

Upvotes: 0

Views: 43

Answers (1)

S.I.
S.I.

Reputation: 3375

I assume you query table products and you check by category_id as below query in your controller. Then try to change your query from:

$ifNoSubCategory = Categories::with('products')->get();

to:

$ifNoSubCategory = DB::table('products')->where('category_id', '=', $categoryId)->get();

Upvotes: 0

Related Questions