2

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?

  • please refer, i hope this will helpful https://stackoverflow.com/questions/24184069/laravel-merge-relationships – Kirit Jan 11 '19 at 06:25

1 Answers1

1

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

Bruno Rodrigues
  • 314
  • 1
  • 4
  • 15