James Parsons James Parsons - 1 month ago 4
MySQL Question

Displaying posts of users the user follows through Laravel relationships

I would like to display the posts of everyone the current user follows, ordered by date desc.

I have a many to many relationship supplying all the people the user is following.

$users = User::find(Auth::user()->id)->follow()->get();

I have a one to many relationship displaying the posts for any user.

$updates = App\User::find(?????)->updates()->orderBy('created_at', 'desc')->get();

The question mark's shows where the followers ID's need to be placed.

I can put the above query inside the for each loop but that obviously works its way through each follower rather than all posts in date order.

I suspect I may need to set a new relationship and work from the beginning. Can anyone advise.

User Model

public function updates()
return $this->hasMany('App\update');

* User following relationship
// Get all users we are following
public function follow()
return $this->belongsToMany('App\User', 'user_follows', 'user_id', 'follow_id')->withTimestamps()->withPivot('id');;;
// This function allows us to get a list of users following us
public function followers()
return $this->belongsToMany('App\User', 'user_follows', 'follow_id', 'user_id')->withTimestamps();;


Update Model

public function user_update()
return $this->belongsTo('App\User');

Thank you.


Since you want the posts, it is probably going to be easier starting a query on the Post model, and then filter the posts based on their relationships.

Assuming your Post model has an author relationship to the User that created the post, and the User has a follower relationship to all the Users that are following it, you could do:

$userId = Auth::user()->id;
$posts = \App\Post::whereHas('author.follower', function ($q) use ($userId) {
        return $q->where('id', $userId);
    ->latest() // built in helper method for orderBy('created_at', 'desc')

Now, $posts will be a collection of your Post models that were authored by a user that is being followed by your authenticated user.