Search code examples
laraveleloquenteloquent-relationship

How to sort data in laravel 7 eloquent using collection map?


I have this peace of code to get comments and replies. I would like to know how can I sort the replies:

$comments = Comment::where([
            ['commentable_type', 'App\Models\Posts\Post'],
            ['commentable_id', $post->id],
            ['parent_id', null]
])->with('replies')
          ->orderBy('created_at', 'desc')
          ->take(10)
          ->get()->map(function($comments) {
                $comments->setRelation('replies', $comments->replies->take(3));                
                return $comments;
});

I tried do this:

$comments = Comment::where([
            ['commentable_type', 'App\Models\Posts\Post'],
            ['commentable_id', $post->id],
            ['parent_id', null]
])->with('replies')
          ->orderBy('created_at', 'desc')
          ->take(10)
          ->get()->map(function($comments) {
                $comments->setRelation('replies', $comments->replies->take(3));                                    
                $comments->setRelation('replies', $comments->replies)->orderBy('created_at', 'desc');
                return $comments;
});

And also

$comments = Comment::where([
            ['commentable_type', 'App\Models\Posts\Post'],
            ['commentable_id', $post->id],
            ['parent_id', null]
])->with('replies')
          ->orderBy('created_at', 'desc')
          ->take(10)
          ->get()->map(function($comments) {
                $comments->setRelation('replies', $comments->replies->take(3)->orderBy('created_at', 'desc'));
                return $comments;
});

But did not works.

Could you help me?

Regards


Solution

  • Assuming that you want the last three replies for each comment - this should work

    $comments = Comment::where([
            ['commentable_type', 'App\Models\Posts\Post'],
            ['commentable_id', $post->id],
            ['parent_id', null]
        ])->with(['replies' => function($query){
            $query->latest();
        }])
        ->get()
        ->map(function($comment) {
            $replies = $comment->replies;
    
            unset($comment->replies);
    
            $comment->setRelation('replies', $replies->take(3));
            
            return $comment;
        });