Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Easier Relation Queries with New Eloquent Methods in Laravel 11.x

Laravel 11.x already has a whereRelation method that lets you query relationships directly. However, there were a few query methods that can be made simpler when using relations.

For instance, the whereDoesntHave method can query records that do not have a relationship. A typical query based on this method looks like this:

User::whereDoesntHave('comments', function ($query) {
    $query->where('created_at', '>', now()->subDay());
})->get();

As you can tell, the above query is a bit verbose since you have to pass a closure to the method, and then you’ll again have to use the where method to define the condition.

A recent Laravel 11.x release attempts to fix this.

A bunch of new methods have been added to the Eloquent query builder that makes querying relationships a lot easier.

For instance, here’s how the previous query can be simplified using the new whereDoesntHaveRelation method with a whereRelation-like syntax.

User::whereDoesntHaveRelation(
    'comments', 'created_at', '>', now()->subDay()
)->get();

Or if you’re checking against a boolean column.

User::whereDoesntHaveRelation(
    'comments', 'approved', false
)->get();

There’s also a new method for morph relations called whereMorphDoesntHaveRelation that works similarly.

User::whereMorphDoesntHaveRelation(
    'comments', [Post::class, Video::class], 'created_at', '>', now()->subDay()
)->get();

Similarly for boolean columns too.

User::whereMorphDoesntHaveRelation(
    'comments', [Post::class, Video::class], 'approved', false
)->get();
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?