Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Brandon.css's avatar

Show all posts from users you follow

I am building a twitter like app and am trying to currently build the news feed like page where i can see all the posts of users I follow.

I have 3 tables: Users, Followers, Posts

The Tables look like this: Users: id Followers: user_id, follower_user_id (user_id is the logged in user, follower_user_id is the user the logged in user is following) Posts: user_id

My models are as follows: User.php

public function posts()
{
    return $this->hasMany('App\Posts');
}

public function following()
{
    return $this->belongsToMany('App\User', 'followers', 'follower_user_id', 'user_id')->withTimestamps();
}

public function isFollowing(User $user)
{
    return ! is_null($this->following()->where('user_id', $user->id)->first());
}

Posts.php

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

I've tried tables joins, but I'm not really good with mysql and databases and my understanding of them are terrible.

If anyone could point me in the right direction, I'd really apprecaite the help :)

0 likes
2 replies
RajS's avatar

It would be a good idea to store an "is following" column for each of your users otherwise you would have to check the "followers" section for every single one of your users every time to see if the logged in user is one of them.

robrogers3's avatar

You can do a join. But for these things unless you have huge data, just use the Eloquent collection methods. Remember to eager load;

so, to get posts of users followed by user id 1;

$posts = User::where('follower_id', 1)->with('following')->first()->following->each->posts;

totally not tested. if it works then eager load both via with('following.posts')

Please or to participate in this conversation.