• Reading time ~ 1 min
  • 05.06.2025

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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297

We shoot down "Shahed" drones every day. Each one downed means lives saved. But we need mobility: a van or a trailer. Every donation = another night under protection.

🚐 Van fundraiser for my unit, 1020 regiment 🎯 Goal: 500,000 ₴
🔗 Donation link 💳 4441 1111 2546 4663