Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Fetch results based on the absence of the relationship in Laravel

 

You may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don't have any comments. To do so, you may pass the name of the relationship to the doesntHave and orDoesntHave methods:

 

$posts = App\Models\Post::doesntHave('comments')->get();

 

If you need even more power, you may use the whereDoesntHave and orWhereDoesntHave methods to put "where" conditions on your doesntHave queries. These methods allow you to add customized constraints to a relationship constraint, such as checking the content of a comment:

 

use Illuminate\Database\Eloquent\Builder;

$posts = App\Models\Post::whereDoesntHave('comments', function (Builder $query) {
    $query->where('content', 'like', 'foo%');
})->get();

 

You may use "dot" notation to execute a query against a nested relationship. For example, the following query will retrieve all posts that do not have comments and posts that have comments from authors that are not banned:

 

use Illuminate\Database\Eloquent\Builder;

$posts = App\Models\Post::whereDoesntHave('comments.author', function (Builder $query) {
    $query->where('banned', 0);
})->get();

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon