eggplantSword's avatar

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

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.

0 likes
8 replies
MarianoMoreyra's avatar

@msslgomez actually, reading again, you should use whereHas instead so you can filter the Products using a whereIn and passing your $products list.

Sorry I can’t write an example for you, as I’m at my phone and it gets hard to write that code hehe

MichalOravec's avatar
Level 75
$categories = Category::whereHas('products', function ($query) use ($products)  {
    $query->whereIn('id', $products->pluck('id'));
})->get();

In Category model you can create an accessor

public function getNameAttribute()
{
    return (app()->getLocale() === 'es' ? $this->es_name : $this->en_name) ?? $this->es_name;
}

Then you can use $category->name without that logic what you have in previous post.

eggplantSword's avatar

@michaloravec Is model function used like this?

$categories->each(function ($item) {
    $item->name = $item->getNameAttribute();
});

Please or to participate in this conversation.