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.

Recent Courses on Laravel Daily

AI Agents/IDEs for Laravel: May 2026 (Claude Code, Codex, OpenCode, etc)

7 lessons
52 min

Testing in Laravel 13 For Beginners

26 lessons
1 h 41 min read

Queues in Laravel 13

18 lessons
1 h 12 min read

No comments yet…