Gazz
Gazz

Reputation: 1075

Display from database if 2 columns match

I am new to Laravel and am currently I am working on a very basic private messaging system.

Currently I am trying to display a page which shows the messages between 2 users (sent and received), however I am only able to display the messages which the user has sent. Here is my viewMessage function in my MessageController file.

MessageController.php

public function viewMessage($recipient_id){

    $user = auth()->user()->id;

    $messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get();

    return view ('pages.messages.view', compact('user', 'messages'));
}

View Blade

<ul>

    @foreach ($messages as $message)

        <li>{{$message->body}}</li>

    @endforeach

</ul>

As you can see from the $messages variable, i have a query builder which should match the sender ID with the ID of the current logged in user. It should also match the recipient ID with the ID of the user from the parameter, however this does not currently work.

I have used dd() and both sender id and recipient id is coming through correctly so I am at a loss as to why this is not working. I am assuming I am probably using the query builder incorrectly?

Thanks

Upvotes: 1

Views: 55

Answers (1)

Ebski
Ebski

Reputation: 235

You are only asking for messages the user sent. You need to also get messages that the user received.

$user = auth()->user()->id;

$messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get();

$receivedMessages= Message::where('sender_id', recipient_id)->where('recipient_id', $user)->get();

Upvotes: 1

Related Questions