Laravel - orderBy in nested relations

eloquent, laravel

Solution

You can pass a closure within the array when calling `with()` to add further query elements to the eager loading query:

Forum::with([
    'comments' => function($q){
         $q->orderBy('created_at', 'desc');
     },
    'comments.user'
])->find($id);

Now you have to specify `comments` and `comments.user` but don't worry it won't run more queries than just `comments.user`.

Problem

I have an eloquent query like this: ``` Forum::with(['comments.user'])->find($id); ``` This returns a nested result `forum -> its comments -> user who commented`. How do I apply `orderBy()` on `comments` table?

Original source