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

mp-webbys's avatar

Eloquent Relationship with 2 other Models and orderBy?

hi, i have an event model and 2 related other models (tasks, states) how can i make the state model is orderedBy name and the states model is ordered by id?

$event = Event::with(['states','tasks'])->findOrFail($id);

thnx

0 likes
8 replies
mightylal's avatar
Level 6
Event::with(['states' => function ($query) {
    $query->orderBy('name');
}, 'tasks' => function ($query) {
    $query->orderBy('id');
}])->findOrFail($id);
1 like
Snapey's avatar

Put orderBy on each of your relationships.

Event model;

    public function states()
    {
        return $this->hasMany(State::class)->orderBy('name','asc'); 
    }

    public function tasks()
    {
        return $this->hasMany(Task::class)->orderBy('id','asc'); 
    }

Just guessing at the models and relationships, hopefully you get the idea

1 like
mp-webbys's avatar

Thnx snapey, this is one solution, but in this case every that order will be that way every time, i fetch the models through the parent one. I think mightylal way is more flexible. Thank you both.

Snapey's avatar

Well just create a new relationship

public function states()
{
    return $this->hasMany(State::class); 
}

public function statesByName()
{
    return $this->hasMany(State::class)->orderBy('name','asc'); 
}
mp-webbys's avatar

But when i call this: $event = Event::with(['states','tasks'])->findOrFail($id);

$event->states is filled automatically by the states() method from the event model, isn't it?

The statesByName() must be called explicit. Or am i wrong?

Snapey's avatar

But when i call this: $event = Event::with(['states','tasks'])->findOrFail($id);

Nothing to stop you;

$event = Event::with(['statesByName','tasks'])->findOrFail($id);
1 like
mp-webbys's avatar

Aaaaaahhhh, now I got it, though the values are the models / tables. Thnx snapey.

mp-webbys's avatar

please can you show me in the docu where i can read more about :with() sometimes i am to stupid to find something there...

Please or to participate in this conversation.