So I am building a messaging system and I would like to display all conversations the user is having and the most recent messages in those conversations
This is what I have
$recentMesssages = Auth::user()->conversations()->get()
->filter(function ($conversation){
return $conversation->messages->last(); //shows the last when I dd()
From the above the return gives me a conversation model not its last message. But when I dd() instead of return I get the last message.
these are the relations from the conversation model
I think you are confused by the filter() method; it filters a Collection based on some criteria and returns an array of items from the Collection which satisfy the criteria.
Using dd()gives you the message because you die and dump on a message object.
Thanks @tykus_ikus . So how do set the criteria to only return the last message i.e the nested relation. At the moment it only returns conversation model and its obvious what that is the case.
I would make add a latest_message attribute to the Conversation model, which would be available on a conversation instance.
// Conversation.php
public function getLatestMessageAttribute()
{
return $this->messages->last(); // 'messages' is the name of the hasMany relationship
}
You can now iterate over your user's conversations collection and display the last message in each conversation:
@foreach(Auth::user()->conversations as $conversation)
{!! $conversation->latest_message !!}
@endforeach