How to eager load a relationship & order it in Laravel

Hello,

Recently I faced this matter, where I have to load a relation and order it at the same time.

Well, thanks to Eloquent, the solution was pretty easy and obvious.

Author
Eager Load

Let's imagine for the moment we have a Ticket & TicketReply models. A Ticket has many TicketReply.

The situation was to to get the ticket, and load the replies with them. So the code would be as follows :

Ticket::query()->with('replies', function (HasMany $relation) {
            return $relation->orderBy('created_at', 'DESC')->get();
        })->find($id);

In this code, we would query the tickets table, and eager load the replies, but we passed a callback to the with function, so it will order the replies by their creation date. Theoretically, we can do anything with the callback, even going further and eager load relationships on the TicketReply model itself.

I hope this little tip has been helpful for you.