What is the opposite of has() method in Laravel?



What is the opposite of has() method in Laravel? | ninjasquad

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.


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.



Source: Internet

Leave a Comment

We are offering free coding tuts

X