feknuolis
feknuolis

Reputation: 45

Display messages between two users. Laravel

I need to display messages between two users. I've created table conversations, it has con_id, user_id, friend_id fields. I don't know how to write logic so that messages will be shown only those who are written between these two users which is in user_id and friend_id fields.

Storing message:

public function store(Request $request, $id)
{
    $conv = new Conversation();
    $conv->user_id = Auth::user()->id;
    $friend = User::where('id', $id)->first();
    $conv->friend_id = $friend->id;
    $conv->message = $request->input('message');
    $conv->save();
}

Upvotes: 1

Views: 1289

Answers (1)

P_95
P_95

Reputation: 145

Get messages where Auth-user is sender (user_id) and receiver is the friend_id, and vice versa. Order by time (assuming you have column created_at).

$sent_by_me = DB::table('conversations')
->select('message', 'user_id as sender_user_id', 'friend_id as receiver_user_id')
->where('user_id', Auth::user()->id)
->where('friend_id', $friend_id);

// messages sent to me by friend
$conversation = DB::table('conversations')
->select('message', 'user_id as sender_user_id' 'friend_id as receiver_user_id')
->where('user_id', $friend_id)
->where('friend_id', Auth::user()->id)
->union($sent_by_me)
->orderBy('created_at', 'asc')
->get(); 

return View::make('show.conversation')
     ->with('conversation', $conversation);

In blade you're the receiver if sender_user_id differs from Auth::user()->id, otherwise you're the sender. Using one-line-if to determine the css style for message. Note: you must check that user really is logged in before you can use Auth::user()->id, otherwise it will fail if user is not logged in. Using middlewares in this case will do it.

@forelse($conversation as $msg)
    <div id="message_{{ $msg->id }}" class="{{ $msg->sender_user_id === Auth::user()->id ? 'sent_message' : 'received_message' }}"> {{ $msg->message }} </div>
@empty
    No messages!
@endforelse

Upvotes: 2

Related Questions