We actually need to do two things:

1. Describe a separate relationship for the latest post in the topic
public function latestPost()
    return $this->hasOne(\App\Post::class)->latest();
2. Then, in our controller, we can do this “magic”
$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');

An example, we have topics table:

Now, let’s show all users order by latest post. If you look at the data, user ID 2 should come first with latest post on 27th day, then user ID 3 with post on 26th day, and then user ID 1 with post on 25th.

$users = User::with('latestPost')->get()->sortByDesc('latestPost.created_at');
foreach ($users as $user) {
    echo $user->id . ' - ' . $user->latestPost->title . ' (' . $user->latestPost->created_at . ')
'; }

The result will be:

Credit to: https://bit.ly/3I7as2c