I'm currently creating a basic private messaging system in Laravel. In my database I have a messages table. Two of the columns are "sender_id" and "recipient_id".
What I am trying to do is use eloquent to go through this table and list in the inbox all the times the current logged in user's id is listed in these columns. I will then use "distinct" to ignore duplicate entries so that the user is only listed once. Using this ID, I can display the username of the recipient so that when the user clicks on the username, it will take them to the message thread for that user.
For the sake of testing, I am only currently retrieving the column "recipient_id" and outputting it into the blade. Here is the line I believe should only output the recipient once despite being found many times in the table.
MessageController
$messages = Message::where('recipient_id', $user)->distinct('recipient_id')->get();
However in the blade, the same user is being output twice (as they have 2 messages found) when I would have expected the distinct function to remove the duplicate entry.
I have also tried
$messages = Message::where('recipient_id', $user)->distinct()->get();
But that also did not work.
If I have received 3 messages from 2 different users, it is outputting something like below:
Messages from:
What it should output
Thanks
Use Laravel Collection and changed code to:
$messages = collect(Message::where('recipient_id', $user)->get());
$messagesUnique = $messages->unique('recipient_id');
$messagesUnique->values()->all();
You can follow this
$payment = Payment::with('invoice','customer')->get();
$payment = $payment->unique('customer_id');
It will return all the unique customer payment data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With