We all know the has() method helps list a number of records with at least a related record in Laravel Eloquent.
For example, below we can get all posts that have at least one comment.
$posts = App\Models\Post::has('comments')->get();
But what would be the opposite of this? How do we get a post that has zero comments as there is no method like noHas().
Luckily Laravel has a solution for this, we can user doesntHave() for this reason.
So your code will be
$posts = App\Models\Post::doesntHave('comments')->get();
This will fetch the posts that have no comments.
Leave a Reply