Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

geerizzle's avatar

Sorting relations of a relation in an Eloquent query?

I have this, and it works fine:

 $full_categories = \App\Category::where('published', true)
    ->with(['panels' => function ($query) { 
    $query->where('published', '=', true);},
    'panels.reasons','panels.tests'])
->get()->toJson();

How do I go about sorting the panels.reasons and panels.tests? In this query only for now.

Is it also possible to set a default order rule on the model?

0 likes
2 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60
public function reasons()
{
    return $this->relationType(RelatedClass::class)->orderBy('column', 'asc|desc');
}

Default sort in your model, applied on relation

1 like

Please or to participate in this conversation.