Laravel Tutorials

Simplify Negative Relation Queries with Laravel's whereDoesntHaveRelation Methods

Published
Simplify Negative Relation Queries with Laravel's whereDoesntHaveRelation Methods image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article
Statamic Mailables Viewer Previews Laravel Emails in the Control Panel image

Statamic Mailables Viewer Previews Laravel Emails in the Control Panel

Read article
Laravel Tackle: Run an AI Coding Agent in Your Laravel App image

Laravel Tackle: Run an AI Coding Agent in Your Laravel App

Read article
Queue::forward(): Reroute Laravel Queues in One Place image

Queue::forward(): Reroute Laravel Queues in One Place

Read article
Laravel Read-Through Filesystem: Lazy Storage Migration image

Laravel Read-Through Filesystem: Lazy Storage Migration

Read article