2
votes

I'm trying to get last row of reference table using laravel eloquent. I have a User model which has a reference to MessageParticipant model (returns all the message subjects the user participating in)

public function messages()
{
 return $this->hasMany(MessageParticipant::class);
}

The MessageParticipantrefers to a MessageSubject model (returns the message subject participants belong to)

public function message_subject()
{
    return $this->belongsTo(MessageSubject::class);
}

The MessageSubjectmodel refers to a Message model (return all the messages within message subject)

public function messages()
{
    return $this->hasMany(Message::class);
}

I want to get the last message of each message subject the user has participated in using a eloquent query. How can I do it?

1

1 Answers

3
votes

Try using whereHas with the latest method:

User::whereHas('message_subject', function ($query) {
    $query->with('messages' => function ($q) {
        $q->latest()->limit(1);
    });
})->get();

Docs