Skip to main content
Tutorial Free

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

February 04, 2023
1 min read

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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.