Skip to content
Advertisement

Laravel sort conversations by last message

I have a Conversation model that has many ConversationMessage models.

Now I want to sort the conversations based on the last message of the conversation. Basically like WhatsApp. How do I build the query?

As a sidenote to my code: Conversation contains a user (user_id) and a company associated (company_id). Company has a belongsToMany relation to user.

That sort the ConversationMessage relation models but not the conversations. How can I sort the Conversations based on the last message?

Advertisement

Answer

You can add a timestamp field like last_message_at to your Conversations model and when a new message is added to that Conversation update that field, then later you can sort the result based on last_message_at.

Or you can filter results in the query like below(Test it see if it works):

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement