Skip to main content
Tutorial Free

Eloquent: has() and doesnthave() - get only rows that have children

January 25, 2017
1 min read
From time to time I write short tips about Laravel, and one of the most popular topics is Eloquent. It has so many "hidden" or poorly documented functionality, one of those is filtering parents by whether they have or don't have children. Let's see an example. Let's say we have Authors and Books, with 1-n relationship - one Author can have one or many Books. Here's how it looks in app\Author.php:
    public function books()
    {
        return $this->hasMany(Book::class, 'author_id');
    }
Now, what if we want to show only those Authors that have at least one book? Simple, there's method has():
    $authors = Author::has('books')->get();
Similarly, there's an opposite method - what if we want to query only the authors without any books? Use doesnthave():
    $authors = Author::doesnthave('books')->get();
It's not only convenient, but also super-easy to read and understand, even if you're not a Laravel developer, right?

Enjoyed This Tutorial?

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

Comments & Discussion

No comments yet…