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

bootstrapguru's avatar

Fetch posts of logged in user and people he is following orderby date

Hello everyone, In short , I am trying to show the posts of user and his followers ordering by latest date. Exactly like Facebook feed.

I have User model with followers and posts methods as follows

    public function followers()
    {
        return $this->belongsToMany('App\User','followers','leader_id','follower_id');
    }
   public function posts()
    {        
      return $this->hasMany('App\Post');
    }

also I have Post model

now I am trying to fetch posts of logged in user and his followers, I tried many ways but couldn't crack it, please help me with this. Thanks in advance for the community with great people

0 likes
8 replies
bootstrapguru's avatar

I have managed to get this but please let me know if there is a better solution, I have a feeling that my solution is not right, I want to run with single eloquent if possible...

    $following = Auth::user()->following()->lists('leader_id')->toArray();
    $following[] = Auth::user()->id;
    $posts = App\Post::whereIn('user_id',$following)->orderBy('created_at','desc')->get();

so I got posts of the user and the people whom he is following..

StormShadow's avatar

@bootstrapguru one way you could do it is

$user = Auth::user();
$userIds = $user->following()->pluck('id')->toArray();
$posts = Post::whereIn('user_id', $userIds)->orWhere('user_id', $user->id)->orderBy('created_at', 'DESC')->get(); 
3 likes
aslam-ep's avatar

@StormShadow If the number of the following people is significantly large then this will become a huge chunk of data check. Is any way to optimize it?

bootstrapguru's avatar

yeah looks almost like my answer but I see you are not attaching logged in user id and also pluck which I see a better alternative, thanks for your answer :) I am going to update this

StormShadow's avatar

Yeah no worries! You posted while I was typing lol Cheers! Yeah that would be great if there was a single query, If you come across one please share :)

StormShadow's avatar
Level 51

@bootstrapguru see here for a nice example of a single eloquent query that can be adapted for your use:

$id = Auth::id();
$posts = App\Post::whereIn('user_id', function($query) use($id)
{
  $query->select('leader_id')
        ->from('followers')
        ->where('follower_id', $id);
})->orWhere('user_id', $id)->latest()->get();
jinxkitt's avatar

i have my post returned API but i only have the user_id and contents of the post but not the name and photo of the author, its on the User model. how am i going to append another json attriubte the name and photo .

Please or to participate in this conversation.