1

So I have been playing around with the structure of a new comment system for my blog using Polymorphic relationships. It all works fine but I am having trouble sorting the comments.

For example, here I get what I need through the controller and pass to the view.

$post = BlogPosts::with('BlogCategories', 'Users', 'BlogTags', 'Comments')
    ->where('slug', $slug)
    ->first();

return view('blog.show', compact('post'));

All that works fine and returns the blog post with the various relations, including the comments.

What I am struggling with is that I want to sort the result so that the comments attached to the post are displayed in descending order.

miken32
  • 42,008
  • 16
  • 111
  • 154
Holo
  • 579
  • 10
  • 26

1 Answers1

0

Actually it was easier than I thought, you can simply sort the relation in the blade template, like this.

@foreach( $post->comments->sortByDesc('created_at') as $comment)

....

@endforeach

Makes sense really.

Holo
  • 579
  • 10
  • 26