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

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(\App\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?

Like our articles?
Check out our Laravel online courses!


  1. whereHas() and whereDoesntHave() methods are very useful tied in with a UNION query.

    E.g I have a query calculating the totals with whereHas and then append a single union row for any missing records with the whereDoesntHave


Please enter your comment!
Please enter your name here