Laravel show my Posts, Followed user posts and Shared posts in a single query

Viewed 257

Currently I can view my Posts and Followed users posts and I want to include my shared posts.

users table: id, name
posts table: id, title, description, user_id
followers table: id, user_id, follower_id
shared_posts table: id, post_id, user_id

This is my query.

 $posts = Post::whereIn('user_id', function($query)
        {       
            $query->select('user_id')
                    ->from('followers')
                    ->where('follower_id', Auth::user()->id);
        })->orWhere('user_id', Auth::user()->id)
            ->with('user')
            ->orderBy('updated_at', 'DESC')->get();

        return view('home')->with('posts', $posts);

I want to add my shared posts in a single query. Thank you.

1 Answers

At User model add this methods:

public function posts()
{
    return $this->hasMany(Post::class, 'user_id', 'id');
}
public function followers()
{
    return $this->hasMany(Follower::class, 'user_id', 'id');
}
public function followers_posts()
{
    return $this->hasManyThrough(Post::class, Follower::class);
}
public function shared_posts()
{
    return $this->hasManyThrough(Post::class, SharedPost::class);
}

And eloquent query:

User::where('id', $foo_if)->with('posts', 'followers', 'followers_posts', 'shared_posts')->first();
Related