Skip to content
Advertisement

Laravel – How to display only those Category who have products?

My aim is to not display the category which don’t have any products as of now.

I have a drop-down list having all the category (level down to sub-category as well)

which giving me the following results.

Electronics
    - media
        - speaker
        - DVDs
    - Computers
Clothing
    - Mens
        - Shirt
        - Jeans
    - Women
Craft

But, I want to achieve following results

Electronics
    - media
        - speaker
    - Computers
Clothing
    - Mens
        - Shirt

The database tables are following

categories

id | name       | parent_id 
-----------------------------
1  | Electronics| null  
2  | media      | 1
3  | Clothing   | null  
4  | Craft      | null
5  | Mens       | 3
6  | Women      | 3
7  | Shirt      | 5
8  | Jeans      | 5
9  | speaker    | 2
10 | DVDs       | 2
11 | Computers  | 1


products

id | p_name                 | p_cat_id 
---------------------------------------
1  | Cotten shirt for men   | 7  
2  | New Jeans bla bal      | 7
3  | Custome gaming pc 1    | 11
4  | Custome gaming pc 2    | 11
5  | Bluetooth speaker      | 9

Category model

public function subCategory(){
    return $this->hasMany(Category::class, 'parent_id');
}
public function products(){
    return $this->hasMany(Product::class,'p_cat_id','id')->where('status','=', 1);;
}

I have tried following to get category list. which gives me all the categories and sub categories

function getCategory() {
    return Category::where([['parent_id', '=', null], ['status', '=', 1]])->orderBy("name", "ASC")->get();
}

Advertisement

Answer

If you need to filter out that only showing category which has least one product:

$categories = Category::with('products')->has('products')->get();

It is a simple function ->has() will check category has any products.

function getCategory() {
   $categories = Category::with('products')->has('products')->get();
   return $categories;
}

UPDATE:

To make it work for sub-categories, I have fixed it for myself as following

in Helper:

function getSubcategory($catid) {
    return  Category::where([['parent_id', '=', $catid], ['status', '=', 1]])
                        ->with('products')->has('products')->get();
}

In, Blade file:

@if(count( getSubcategory( $category->id )) > 0)
    @include('category.subCategoryList',['subcategories' => getSubcategory( $category->id )])
@endif

Hope it will working for others too.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement