Eloquent: Get Data From One Table That Doesn't Exist in Another Table

If you have two tables with a hasOne or hasMany relationship between them, and you want to query a row that is missing from the second table, you can use doesntHave() in Eloquent.

app/Models/Post.php:

public function comments()
{
return $this->hasMany(Comment::class);
}

Then, somewhere in the Controller:

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

Under the hood, it will perform this SQL query:

select * from posts
where not exists (
select * from comments where posts.id = comments.post_id
)

It is the opposite of querying the records present in BOTH tables:

Post::has('comments')->get();

Read more in the official Laravel docs.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses