-4

I made table conversations and table messages, each conversation has many messages, and i want to show the latest message a conversation has, so i use this

$conversation->messages->last()->body

its return the last message in the record but not the latest,

this is my record

database record

the latest messages not the last record , when i insert new message its not in the last record but inserted at some random order, that make the last() not work properly,

Blue Moon
  • 31
  • 9

2 Answers2

2

You want to sort a collection and get its last element.

Either sort in ascending order and take the last element:

$conversation->messages->sortBy('created_at')->last()->body

Or sort in descending order and take the first element:

$conversation->messages->sortByDesc('created_at')->first()->body

Whichever you consider more readable.

Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73
0

Attach timestamp column in your table and then select messages order by timestamp desc.

You will get last message.

devil_sm
  • 31
  • 6