TL;DR: Need latest message from each sender.
In my Laravel application I have two tables:
Users:
Messages:
I like a simpler approach which is mentioned here.
In your User
model additionally to existing messages()
relationship, add this relationship
public function latestMessage()
{
return $this->hasOne(Message::class, 'recipient_id')->latest();
}
Then when you query simply query like this.
$messages = User::with('latestMessage')->get();
$messages
contains latest message per user.
Edit
In order to order the result by datetime/id you could do it like this.
$messages = User::with(['latestMessage' => function($message) {
$message->orderBy('id', 'desc');
}])->get();
$messages
contains latest message per user ordered by id
. Refer this answer