Simplified Relation Queries in Laravel with New whereDoesntHaveRelation Methods
Need to write cleaner queries for missing relations? Laravel introduces new methods to simplify negative relation queries, making your code more readable and maintainable.
Basic Usage
Query records without specific relations:
// Simple relation query
User::whereDoesntHaveRelation(
'comments',
'created_at',
'>',
now()->subDay()
)->get();
// Morph relation query
User::whereMorphDoesntHaveRelation(
'comments',
[Post::class, Video::class],
'is_approved',
false
)->get();
Real-World Example
Here's how you might use it in a user management system:
class UserManager
{
public function findInactiveUsers()
{
return User::whereDoesntHaveRelation(
'logins',
'created_at',
'>',
now()->subDays(30)
)->get();
}
public function getPendingVerification()
{
return User::whereDoesntHaveRelation(
'verifications',
'verified_at',
'!=',
null
)->get();
}
public function getUnengagedUsers()
{
return User::whereMorphDoesntHaveRelation(
'interactions',
[Comment::class, Like::class, Share::class],
'created_at',
'>',
now()->subMonth()
)->get();
}
public function cleanupInactiveAccounts()
{
return User::query()
->whereDoesntHaveRelation('posts', 'id', '!=', null)
->whereDoesntHaveRelation('comments', 'id', '!=', null)
->whereDoesntHaveRelation(
'logins',
'created_at',
'>',
now()->subYear()
)
->delete();
}
}
These new methods make your relation queries more concise and readable.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!