TL;DR: Need latest message from each sender.
In my Laravel application I have two tables:
Users:
Messages:
This is the most "Eloquent way" I have found of doing this:
In User model:
public function messages() {
return $this->hasMany(Message::class, 'recipient_id');
}
public function latestMessagePerSender()
{
return $this->messages()
->whereNotExists(function ($query) {
$query->from('messages AS m2')
->whereRaw('m2.sender_id = messages.sender_id')
->whereRaw('m2.created_at > messages.created_at');
});
}
Then just $user->latestMessagePerSender