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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article