Using sortBy() collection method for sorting relation after eloquent query if required

Suppose there is a relation Post hasMany comments.

By default laravel does sorting by desc for child relation.

However, if we want to sort it by ascending we need to use collection method sortBy() like following snippet

Step 01: In Controller fetching comments with specific post

$post = Post::with(['comments'])->findOrFail(4);

Step 02: In View: using sortBy()

@forelse( $post->comments->sortBy('created_at') as $comment )
    {!! $comment->comment_text !!}
@empty
    No comments yet.
@endforelse

Example above, shows list of comments posted in ascending order that is from oldest to newest

Last note, there is also a method sortByDesc() which performs other way around that is it sorts list in descending order.

In both sortBy() and sortByDesc() they take property as parameter on which they perform either ascending or descending

Related Posts


Using collection method reduce()