How to get records orderBy in Laravel relationship

When you implement Laravel's eloquent relationship, you can get all the related records. But sometimes you want to get records order by specific field on Laravel relationship.

In this article, I will show you how you can chain additional methods in eloquent relationship. Suppose you want to get records in order by specific field, then you can add orderBy() method on relationship.

<?php

public function comments()
{
    return $this->hasMany(Comment::class, 'post_id', 'id')->orderBy('id', 'desc');
}

There is also another way you can implement if you want to get orderBy records only once with relationship. Here is relationship model method in model.

<?php

public function comments()
{
    return $this->hasMany(Comment::class);
}

And in your controller class, you can do like the below:

<?php

public function index()
{
    $data = Post::with(['comments' => function ($query) {
        $query->orderBy('id', 'desc');
    }])->get();
}

This way, you can get records order by specific field. I hope you liked this article.

Tags: