TheUnreal
TheUnreal

Reputation: 24492

Laravel ordering a relation

I have the following query to get a thread and all the messages:

$thread = Thread::with('messages.user.zone')
            ->with('participants.user')
            ->findOrFail($id);

.

I want to get the thread messages ordered by it's created_at property desc.

Currently the order is from the oldest to the new (asc)

How I can do that? Tried ->orderBy('messages.created_at') with no luck

Upvotes: 2

Views: 59

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

This should work:

->with(['messages' => function($q) {
    $q->orderBy('created_at', 'desc');
}, 'messages.user.zone'])

Upvotes: 7

Related Questions