Hi @msslgomez
Just query for relationship existence:
$categories = Category::has('products')->get();
docs: https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence
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.
$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.
Please or to participate in this conversation.