Laravel 11.37.0: New Query Methods for Missing Relationships
- New Query Methods in Laravel 11.37.0: Enhancing Relation Queries
- The Problem: Handling Missing Relationships
- The Solution: New Methods for Missing Relationships
- OR Variants
- Supported Versions
New Query Methods in Laravel 11.37.0: Enhancing Relation Queries
Laravel has introduced another powerful enhancement to Eloquent in its latest 11.37.0 release. Thanks to a contribution by Andrey Helldar, developers can now use the new whereDoesntHaveRelation
and whereMorphDoesntHaveRelation
methods to simplify queries involving relationships.
These additions make it significantly easier to retrieve models that do not have a specific relationship, providing a cleaner, more intuitive approach compared to previous workarounds.
The Problem: Handling Missing Relationships
Before this update, Laravel provided methods such as whereDoesntHave
and whereDoesntHaveMorph
for querying models with specific relationships. However, developers often needed verbose and complex logic to query models that lacked a relationship.
The Solution: New Methods for Missing Relationships
The whereDoesntHaveRelation
and whereMorphDoesntHaveRelation
methods address this gap by introducing a simple way to query models missing specific relationships.
Example 1
// BeforeUser::whereDoesntHave('comments', function ($query) { $query->where('created_at', '>', now()->subDay());})->get(); // AfterUser::whereDoesntHaveRelation( 'comments', 'created_at', '>', now()->subDay())->get(); User::whereDoesntHaveRelation( 'comments', 'is_approved', false)->get();
Example 2
// BeforeUser::whereDoesntHaveMorph('comments', [Post::class, Video::class], function ($query) { $query->where('created_at', '>', now()->subDay());})->get(); // AfterUser::whereMorphDoesntHaveRelation( 'comments', [Post::class, Video::class], 'created_at', '>', now()->subDay())->get(); User::whereMorphDoesntHaveRelation( 'comments', [Post::class, Video::class], 'is_approved', false)->get();
OR Variants
In addition to these methods, Laravel also introduces their OR
variants:
-
orWhereDoesntHaveRelation
-
orWhereMorphDoesntHaveRelation
These methods allow you to combine "doesn't have relation" queries with other conditions for more complex use cases.
Supported Versions
This feature is available starting with Laravel 11.37.0, further solidifying the frameworkโs focus on developer experience and clean, maintainable code. To explore the technical details, visit the GitHub pull request.
Stay Updated.
I'll you email you as soon as new, fresh content is published.