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

andrecuellar's avatar

How to make a query with relations and order it by date of the relation in Laravel 9

Hello,

I have the User model, I also have the Post model In Laravel 9

I would like to get 4 users through the newest posts of my entire Post model (taking into account that even a single user could have n number of newest posts) and then get the posts of each user (two for each user) obtained through of the relationship, something like that in case it is not understood very well

Alt image

I have no problem getting the relationship from the blade, but what I can't get are the 4 users with the newest posts

User model

public function posts()
{
    return $this->hasMany(Post::class);
}

Post model

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

I was doing this query, it works, but I think that is not the best way

public function getUsersByNewerPosts()
{
    return User::query()
        ->whereHas('posts', function ($query) {
            $query->where('state', PostStateEnum::PUBLISHED);
        })
        ->orderByDesc(
            Post::select('updated_at')
                ->whereColumn('user_id', 'users.id')
                ->where('state', PostStateEnum::PUBLISHED)
                ->orderByDesc('updated_at')
                ->limit(1)
        )
        ->take(4)
        ->get();
}
0 likes
1 reply

Please or to participate in this conversation.