Unable to merge two Eloquent collections

Viewed 499

I have a table named messages in my database and, it has five columns as:

id | sender_id | receiver_id | message | sent_at

And, in my model User, I have a function that looks like this:

    public function messages(){

      $sent_messages = $this->hasMany(Message::class, "sender_id");

      $received_messages = $this->hasMany(Message::class, "receiver_id");

      $messages = $sent_messages->merge($received_messages);

      return $messages;

    }

I opined that it would work but it didn't. The error I get is:

BadMethodCallException with message 'Call to undefined method Illuminate/Database/Query/Builder::merge()'

So, what did I do wrong and what can I do to get all the messages if its either sent by me or received by me?

1 Answers

In order to have a Collection you must use the ->get() method. Otherwise you have the relation objects and you can't merge them ;)

Related