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

ahmadbadpey's avatar

Order parent model based on child model creation date in eager load laravel eloquent

I have a Conversation model like this :

    class Conversation extends Model
    {
            protected $primaryKey = 'conversation_id';
            public function questions (){
                return $this->hasMany('App\Question','conversation_id','conversation_id');
            }

        public function latestQuestion ()
        {
            return $this->hasOne('App\Question','conversation_id','conversation_id')
                ->orderBy('created_at', 'desc');
        }

    }

And a Question model like this :

    class Question extends Model
        {    
            protected $primaryKey = 'question_id';
    
            public function conversation ()
            {
                return $this->belongsTo('App\Conversation', 'conversation_id', 'conversation_id');
            }
    }

As you can see each Conversation can have some Question.

Furthermore, Conversation model has a latestQuestion relationship that fetches latest Question for that Conversation.

Now I want to list all Conversations with their latest question.

For that I wrote :

    $conversations =
        Conversation::
        with('latestQuestion')
        ->orderBy('created_at','desc')
        ->get();

above code, orders conversations by their created_at field.

But I want to make a list of Conversations that conversations with new question be on top of list. in fact I want to order Conversations based On latest Question created_at field But I do not know How can I do that?

0 likes
4 replies
vipin93's avatar
$conversations =
        Conversation::
        with('latestQuestion')
        ->latest()
        ->get();
ahmadbadpey's avatar

@SaeedPrez Are cases that can change updated_at field of a conversation. for example change title or any other field of that and this causes some conversations come up without any new questions. right?

SaeedPrez's avatar
Level 50

@ahmadbadpey

Yes, but there are a few ways to do what you want.

You could use model event binding (or simpler put it in the question controller's create method), when a new question is created, update last_question_at column on Conversation.

Another option would be to join the tables ...

It all depends on what you need..

1 like

Please or to participate in this conversation.