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

Tutorial last revisioned on August 17, 2022 with Laravel 9
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?

No comments or questions yet...

Like our articles?

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

Recent Premium Tutorials