To my knowledge, the method with impatience of loading with starts the second request. That's why you cannot achieve what you want with a reliable with download .
I think the join method combined with the relationship method is a solution. The following solution is fully tested and works well.
// In User Model public function channels() { return $this->belongsToMany('App\Channel', 'channel_user') ->withPivot('is_approved'); } public function sortedChannels($orderBy) { return $this->channels() ->join('replies', 'replies.channel_id', '=', 'channel.id') ->orderBy('replies.created_at', $orderBy) ->get(); }
You can then call $user->sortedChannels('desc') to get a list of channels by editing the created_at attribute.
For a channel type condition (which may or may not have answers), simply use the leftJoin method.
public function sortedChannels($orderBy) { return $this->channels() ->leftJoin('replies', 'channel.id', '=', 'replies.channel_id') ->orderBy('replies.created_at', $orderBy) ->get(); }
Edit:
If you want to add the groupBy method to the query, you should pay particular attention to your orderBy . Because of the nature of Sql , the Group By clause is executed first before the Order By clause. For more on this issue, see this question on the stack .
So, if you add the groupBy method, you should use the orderByRaw method and should be implemented as follows.
return $this->channels() ->leftJoin('replies', 'channels.id', '=', 'replies.channel_id') ->groupBy(['channels.id']) ->orderByRaw('max(replies.created_at) desc') ->get();