Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ebukz's avatar

Eloquent filter returns wrong Model

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

 #relations: array:4 [▼
        "pivot" => Pivot {#469 ▶}
        "user" => Collection {#475 ▶}
        "messages" => Collection {#291 ▶}
        "participants" => Collection {#439 ▶}

Can anyone see what I am missing ?

0 likes
6 replies
tykus's avatar

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.

ebukz's avatar

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.

Do you know how to return the nested relations ?

tykus's avatar

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         
ebukz's avatar
ebukz
OP
Best Answer
Level 1

Thanks @tykus_ikus I used your suggestion to make some quick fixes.

this is what I did

public function messages() {
        return $this->hasMany(Message::class);
    }
public function getLastestMessage()
    {
        return $this->messages()->get()->last(); // changed this to use relation to retrieve the last in collection
    }

then you can use as follows:

foreach(Auth::user()->conversations as $conversation){
       echo $conversation->getLastestMessage();

    }

1 like
tykus's avatar

You don't need to $this->messages()->get() because you already have a collection from $this->messages

Please or to participate in this conversation.