1
votes

Having these 3 tables:

users

  • user_id
  • first_name
  • last_name
  • etc.

posts

  • post_id
  • title
  • body
  • etc.

posts_users

  • post_id
  • user_id

The post - user relation means that a user is following a post.

The simplest way of listing posts would be:

$posts= Posts::all();

foreach ($posts as $post)
{
    var_dump($post->title);
}

But when listing posts I would love to also query if the current user (say user_id = 5) is following each post.

So for each post I would have post_id, title, ..., is_following [0 or 1].

I can do this using simple SQL, but can this be done the Eloquent way?

2

2 Answers

1
votes

Maybe try eager loading the users and then for each post, loop through the users that are following that post looking for the user id.

$posts = Post::with('users')->get();

foreach($posts as $post) {
    echo $post->title;
    foreach($post->users as $user) {
        if($user->id == $user_id) {
            echo 'User with id of '.$user_id.' is following this post.';
            break;
        }
    }
}
2
votes

Assuming that you have the Post / User relationship defined on the User Model using hasMany('Post'), you can check if the current Post is in the user's followed posts using contains():

$followed_posts = $current_user->posts();

if ($followed_posts->contains($current_post->id))
{
    // This Post is being followed by the User
    // .... Do something .... :)
}