Search code examples
phpmysqllaraveleloquent-relationship

Show only Followed users post using laravel eloquent relationship


I have 3 model User, Follow, and Post

and these relations are like:

User model:

public function userPosts()
{
        return $this->hasMany('App\Model\User\Post');

}
public function follows()
{
    return $this->hasMany('App\Model\User\Follow','user_id');

}
public function fans()
{
    return $this->hasMany('App\Model\User\Follow','follow_id');

} 

Post Model

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

Follow Model

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

Every post belong to some user. and I have a follow list where user have there following user. in follow model there are 2 columns, user_id the user whom follow and follow_id who follow the user.

now I want to show the post in newsfeed there I want to show the post of user I followed and my post only.

How can I show them with Laravel eloquent relationship I am using Laravel 7.2


Solution

  •         Post::where(function ($query) {
                //generating followers and own user_id array
                $followers = Follow::where('user_id', Auth::user()->id)->get();
                $followers_and_me = [];
                array_push($followers_and_me, Auth::user()->id);
                foreach ($followers as $item) {
                array_push($followers_and_me, $item->follow_id);
            }
    
            //query for specific posts
            for ($i =0; $i<count($followers_and_me); $i++) {
                $query->orWhere('user_id', $followers_and_me[$i]);
            }
    
            })->orderBy('id', 'desc')->paginate(5);
    

    Try this one