S.I.
S.I.

Reputation: 3375

Hiding empty categories in Laravel

How can I hide empty categories when I query to display them? Empty categories are those that no products are assigned to them.. Here is my controller

    public function showSubCats($categoryId) {

         $subcats = SubCategories::where('category_id', '=', $categoryId)->get();
         return View::make('site.subcategory', [            
             'subcats' => $subcats
         ]); 
}

Here is the view

@if(count($subcats) > 0)
     <div class="row">
         @foreach($subcats as $i => $subcategory)   

              // display categories

         @endforeach             
@else
         There is no products assigned to this category                  
     </div>

@endif

This is my SubCategories model

public function products()
{
    return $this->hasMany('Product', 'category_id');
} 
public function subcategories()
{
    return $this->hasMany('SubCategories', 'category_id');
}   
public function lowestProduct() {
    return $this->products()->selectRaw('*, max(price) as aggregate')
    ->groupBy('products.product_id')->orderBy('aggregate');
}

In product table I have column which is sub_cat_id and holds category in which is assigned. If is 0 is not assigned to any category.

How can I hide empty categories now?

Upvotes: 1

Views: 837

Answers (1)

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11310

You should use where in addition to your model

return $this->hasMany('Action')->where('sub_cat_id', 1);

Note :

I believe that you neeed to take the records only that has sub_cat_id as 1. If not change it to 0 or accordingly.

Hope this helps you

Upvotes: 1

Related Questions