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

Galavant's avatar

Ordering multiple relationships on created_at date

I am calling a lot of relationships through my activity feed model --- however, I want all of them to be ordered by the created_At date.

I can't seem to succeed with this. anyone has an idea how to do this?

$activities = Activity::where('relation_id','=',$request->id)->with('reactions.user')->with('posts.assignedUsers')->with('notities.user')->with('cat')->with('relations')->orderBy('created_at','desc')->get();
0 likes
3 replies
zion's avatar
zion
Best Answer
Level 9
$activities = Activity::where('relation_id','=',$request->id)
->with(['reactions.user' => function($query) {
    $query->latest();   
},
'posts.assignedUsers' => function($query) {
    $query->latest();
},
'notities.user' => function($query) {
    $query->latest();
},
'cat' => function($query){
    $query->latest();
},
'relations' => function($query){
    $query->latest();
}])
->get();
Galavant's avatar

I've implementated @zion 's query. It does order things, but still not as desired

Everything stems from the activity_feed. The activity feed has one to one relationships with posts, reactions and notities.

        activity_feed

posts       reactions     notities

All 3 of the posts,reactions and notities will be submitted in random orders.

now I need to get all the activities, but via eager loading, need to load them in order to the activity feed.

It seems that it orders posts, reaction and notities seperately.

skimuli's avatar
  1. You can use global scopes[https://laravel.com/docs/5.6/eloquent#global-scopes], that whenever data is fetch is in the orderly manner.

2(or). You can attached latest() or ordyby('create_at', 'ASC') directly on the each relationship.

public function reactions(){
    return $this->hasMany(App\Reaction::class)->latest();
}

Please or to participate in this conversation.