msslgomez
1 month ago

Get model items included in relationship (categories that have products)

Posted 1 month ago by msslgomez

I have an online store and I was wondering if I could show only the categories that have products from the list of products and the relationship.

Right now this is how I bring the products and categories, I would like to get only the categories that the products in $products have, the Product has a categories relationship to get that info

 $products = Product::whereHas('inventorySumQuantity', function ($query) {
            $query->where('quantity', '>', 0);
})
            ->where('type', 'glassware')
            ->get();

$new = Product::whereHas('inventorySumQuantity', function ($query) {
            $query->where('quantity', '>', 0);
})
            ->where('type', 'glassware')
            ->orderByDesc('created_at')
            ->take(10)
            ->get();

$categories = Category::all();
$categories->each(function ($item) {
    if (App::getLocale() === 'es') {
        $item->name = $item->es_name;
    } else {
        if ($item->en_name != null){
            $item->name = $item->en_name;
        } else {
            $item->name = $item->es_name;
        }
    }
});

How can I do this? Or is this not recommended, the reason behind it is that the user can click on the shown categories to see all the products that belong to that category but if it's empty I don't see a real reason to show the category.

Please sign in or create an account to participate in this conversation.