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.
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply