Laravel - Relationships - Querying Relationship Absence
When retrieving model records, 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:
use App\Models\Post;
$posts = Post::doesntHave('comments')->get();
If you need even more power, you may use the whereDoesntHave
and orWhereDoesntHave
methods to add additional query constraints to your doesntHave
queries, such as inspecting the content of a comment:
use Illuminate\Database\Eloquent\Builder;
$posts = Post::whereDoesntHave('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
})->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; however, posts that have comments from authors that are not banned will be included in the results:
use Illuminate\Database\Eloquent\Builder;
$posts = Post::whereDoesntHave('comments.author', function (Builder $query) {
$query->where('banned', 0);
})->get();