Search code examples
phplaravellaravel-5eloquentunique

List only unique id's from 2 columns


I am building a basic private messaging system in Laravel and want to display a list of message threads between 2 users (to the user who is logged in) as a basic inbox.

At the moment I have all messages stored in 1 table. The table contains the "sender_id" and the "recipient_id" as well as the message contents.

To retrieve the list of messages to display in the inbox, I am currently doing this in the controller:

    //Authenticate the user
    $user = auth()->user()->id;

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

    $messageThreads = $messagesReceived->merge($messagesSent);

In the blade, to display the list of threads I am doing:

            <ul class="list-group">

            @foreach ($messageThreads as $message)

            @if($message->user->id != $user)

            <li class="list-group-item"><a href="/messages/view/{{$message->user->id}}">{{$message->user->displayName}}</a></li>

            @else

            <li class="list-group-item"><a href="/messages/view/{{$message->recipient->id}}">{{$message->recipient->displayName}}</a></li>

            @endif

            @endforeach

        </ul>

As expected, this is just displaying the names of the users which the user has messaged or received messages from as well as a link to the thread but if the user has had multiple messages between each other, their name will obviously display multiple times.

Example of how its currently outputting

  • User 1 Thread
  • User 1 Thread
  • User 1 Thread
  • User 2 Thread
  • User 2 Thread
  • User 3 Thread
  • User 3 Thread

How it should output:

  • User 1 Thread
  • User 2 Thread
  • User 3 Thread

I want to be able to make sure the name & link to the thread is only listed once.

I have tried using distinct() and unique() however because the sender_id & recipient_id are seperate columns, i still get duplicate results.

How would I able to overcome this.

Thanks


Solution

  •     $recipientIds = Message::select('recipient_id')->where('sender_id', $user)->get()->pluck('recipient_id');
    $senderIds = Message::select('sender_id')->where('recipient_id', $user)->get()->pluck('sender_id');
    
    
    $userIds = array_unique(array_merge($recipientIds , $senderIds ));
    $users = User::whereIn('id', $userIds)->keyBy('id');
    
    // view
    @foreach($users as $user) 
        <li class="list-group-item"><a href="/messages/view/{{$user->id}}">{{$user->displayName}}
    @endforeach
    

    Credit: https://laracasts.com/discuss/channels/laravel/list-only-unique-ids-from-2-columns