Querying a hasMany through a belongsToMany

Posted 1 month ago by Sultenhest

Hi guys

I'm currently practicing my Laravel skills by building a Twitter clone and i'm still relatively new at building eloquent queries.

I'm stuck building the "feed", which should consists of the statuses of the other user profiles the given user is following.

This is what my models looks like:

User.php

public function statuses()
{
    return $this->hasMany(Status::class)->latest('updated_at');
}

public function following()
{
    return $this->belongsToMany(User::class, 'follows', 'follower_user_id', 'followed_user_id');
}

public function followers()
{
    return $this->belongsToMany(User::class, 'follows', 'followed_user_id', 'follower_user_id');
}

Status.php

public function user()
{
    return $this->belongsTo(User::class);
}

This is what the MySQL query looks like:

SELECT statuses.*
FROM follows
INNER JOIN statuses ON follows.followed_user_id = statuses.user_id
WHERE follower_user_id = 151
ORDER BY statuses.created_at DESC
LIMIT 15;

Where 151 is the current user id and the limit is a pseudo pagination.

My current attempt at eloquent looks like this

auth()->user()->following()->with('statuses')->orderBy('created_at', 'desc')->paginate(15);

It is querying the correct followings along with ALL of their statuses, and its ordering by user.created_at and not status.created_at.

What have i missed?

Please sign in or create an account to participate in this conversation.