Eloquent: filter only rows which has related "children" rows

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');

    // ...

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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 42 courses (796 lessons, total 45 h 33 min)
  • 49 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials