How do I write the following SQL query in Laravel using Eloquent?

Viewed 147

I want to write a query in Laravel to retrive all the posts that a particular user has viewed. The user_id and the post_id is saved in the table named WatchHistory.

SELECT *
FROM Post
WHERE post_id = (
     SELECT post_id
     FROM WatchHistory
     WHERE user_id = $user_id
);

I tried the following :

$posts = Post::whereIn('post_id', function($query){
        $query->select('post_id')
            ->from(with(new WatchHistory)->getTable())
            ->where('user_id',$user_id);
        })->get();

But it gives me an error that the variable user_id is not defined.

2 Answers
Related