mercredi 23 mai 2018

Laravel eloquent sort by latest unique entry

I'm currently creating a basic inbox for a private messaging system which only displays the users which the logged in user has been in contact with if messages between the user and recipient exist. (Similar to how your standard instant messenger works)

The way I am getting this list is to check the messages table to see if any messages between the two users exist. If it does then list this in the inbox but since there will be many messages between the user, I am using a Laravel collection and the unique function to only display a recipient once. The user then can click on this recipient to see the message thread.

The issue I am having with is being able to sort this list by the latest message (e.g. sort by created_at)

How am I able to order this in order of the latest entry so that the most recent messages display at the top of the list in the inbox. Here is the code I using in my controller to get the list of recipients:

    $messages = collect(Message::where('recipient_id', $user)->orderBy('created_at', 'desc')->get());

    $messagesUnique = $messages->sortBy('created_at')->unique('sender_id');

    $messagesUnique->values()->all();

Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2IDNDsw
via IFTTT

Aucun commentaire:

Enregistrer un commentaire