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!

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here