max234435
max234435

Reputation: 567

Group Conversation by latest message Laravel

I can't seem to figure this out since mysql is not my strong suit. I've done a bit of research here but can't put two and two together, so I'm turning to the community for some help.

I am building a chat function inside my Laravel app where two users can talk to each other. I can't figure out how to build the inbox (group the conversations together) portion of things. I've figured out how to get last message grouped by sending it.

The following is inside my User Model:

public function lastMessages() {
    return $this->hasMany('App\Message', 'recipient_id')
        ->select('*')
        ->join(DB::raw('(Select max(id) as id from messages group by author_id) LatestMessage'), function($join) {
            $join->on('messages.id', '=', 'LatestMessage.id');
        })
        ->orderBy('created_at', 'desc');
}

My messages table consists of the following: author_id, recipient_id, messaged, viewed.

What I need to do is group messages, whether incoming our outgoing and display the latest message as inbox entry and once I click on that messages, the rest of the conversation pops up on the page.

My current sql shown above only gives me 1 last message, not the whole conversation.

Thanks in advance for all the help.

Upvotes: 0

Views: 634

Answers (1)

Nitesh Verma
Nitesh Verma

Reputation: 2500

Firstly, I think you should keep the relationship function separate from logical(query) function. If I understood your question correctly , you should do something like this :

Message::where('recipient_id',$userid)->orWhere('author_id',$userid)->orderBy('created_at','desc')->get();

This will give you messages send or received by user. Please clarify your question with Author and Message models if this is not what you want.

Upvotes: 0

Related Questions