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();
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.