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.

JavaScript

But, I want to achieve following results

JavaScript

The database tables are following

JavaScript

Category model

JavaScript

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

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

UPDATE:

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

in Helper:

JavaScript

In, Blade file:

JavaScript

Hope it will working for others too.

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