Simple use-case: you want to filter only those categories which have at least one product. Or course, you write Category::with(‘products’)->… but how do you filter out those empty categories? Those with no product? There’s an app function for that: has().
Let’s show the full code.
app\Category.php:
class Category extends Model { // ... public function products() { return $this->hasMany('App\Product'); } // ... }
app\Http\Controller\CategoriesController.php:
function getIndex() { $categories = Category::with('products')->has('products')->get(); return view('categories.index', compact('categories')); }
So, as you can see, it’s a simple filter-function ->has(‘products’) – it will filter out the categories without products.
Why not a Category::has(‘products’)->get() ? It’s a simpler notation, isn’t it?
Well, I want to take categories WITH products to view how many products are there in category, like Clothing (53), Books (100) etc. But agree that I didn’t put that detail into the article, well spotted Marius.
Thanks for sharing.
The inverse of has method is also usefull : doesntHave()
How about if you filter ‘product’, and the product return an empty result ?
I dont want to display the category if the product return an empty result ? using ->has got still no effect for me …
Thx
how to get list of Category having only one product?
Great knowledge