Skip to main content
Tutorial Free

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

July 14, 2015
1 min read
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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Laravel Coding with AI Agents: Cursor, Claude Code, Codex

5 lessons
1 h 01 min

Laravel Modules and DDD

16 lessons
1 h 59 min

Laravel 12 For Beginners: Your First Project

15 lessons
1 h 32 min

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.