G
G
galyasokolova2019-09-26 11:42:58
MySQL
galyasokolova, 2019-09-26 11:42:58

How to select the last entry in each group in Laravel?

There is a table with messages, the structure is simple: id, sender, recipient, chat_id
I need to display the last message in each of the chats
. Grouping by chat_id via ->groupBy('chat_id') gives the first entry.
->orderBy('id','desc') doesn't work here.
How to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kokhan, 2019-09-26
@galyasokolova

And if you try by the maximum id?
max('id')

J
jazzus, 2019-09-26
@jazzus

Make hasOne relation in Chat model

public function lastMessage()
{
  return $this->hasOne('App\Models\Message','chat_id', 'id')->latest();
}

In the controller in the template
@foreach ($chats as $chat)
  {{ $chat->lastMessage->name }}
@endforeach

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question