Bappy
Bappy

Reputation: 111

Laravel select the last row of linked table using eloquent relationship

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?

Upvotes: 2

Views: 146

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

Try using whereHas with the latest method:

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

Docs

Upvotes: 3

Related Questions