try this
use App\Models\Category;
use Illuminate\Database\Eloquent\Builder;
// Get all categories with the count of products
$categoriesWithProductCount = Category::withCount(['products' => function (Builder $query) {
$query->selectRaw('distinct product_id'); // Ensure distinct products are counted
}])->get();
// Filter out categories with zero product count and their parents
$categoriesWithProductCount = $categoriesWithProductCount->filter(function ($category) {
return $category->products_count > 0 || $category->parent_id == null;
});
// You can now use $categoriesWithProductCount to display the menu