Laravel introduces new methods to streamline negative relation queries, making it easier to find records that lack specific relationships while maintaining clean, readable code.
The new whereDoesntHaveRelation methods provide a concise way to query records without specific relations:
User::whereDoesntHaveRelation(
'posts',
'published_at',
'>',
now()->subWeek()
)->get();
User::whereMorphDoesntHaveRelation(
'activities',
[Comment::class, Review::class],
'is_featured',
true
)->get();
These methods prove particularly valuable in content management systems:
class ContentManager
{
public function findDormantAuthors()
{
return User::whereDoesntHaveRelation(
'articles',
'published_at',
'>',
now()->subDays(60)
)->get();
}
public function getUnmoderatedContent()
{
return Article::whereDoesntHaveRelation(
'moderations',
'reviewed_at',
'!=',
null
)->get();
}
public function getUnpopularContent()
{
return Article::whereMorphDoesntHaveRelation(
'reactions',
[Like::class, Share::class, Bookmark::class],
'created_at',
'>',
now()->subMonth()
)->get();
}
public function archiveStaleContent()
{
return Article::query()
->whereDoesntHaveRelation('comments', 'id', '!=', null)
->whereDoesntHaveRelation('views', 'id', '!=', null)
->whereDoesntHaveRelation(
'updates',
'created_at',
'>',
now()->subMonths(6)
)
->update(['status' => 'archived']);
}
}
These new methods eliminate the need for complex whereDoesntHave closures, making negative relation queries more intuitive and maintainable while improving code readability.