1
public function chats()
{
    return $this->hasMany('App\Chat','sender_id')->orWhere('receiver_id',\Auth::id());
}

My requirement is that i want to fetch messages that being sent or received by User. how i can do it ?

2 Answers 2

1

The following code should do the trick:

public function chats()
{
  return $this->hasMany('App\Chat','sender_id')->union($this->hasMany('App\Chat','receiver_id'));
}

This will return a relation that is a union of 2 queries - one that fetches chat messages where given user is the sender and another one where given user is the receiver.

You can now access user's chats with $user->chats.

Sign up to request clarification or add additional context in comments.

Comments

0

You were very close. hasMany() accepts chained where() and orWhere() calls, so I would make that query like this:

public function chats()
{
    return $this->hasMany('App\Chat')
        ->where('sender_id', \Auth::id())
        ->orWhere('receiver_id', \Auth::id());
}

Once this is correctly set up, you can use $users->chats to access a list of chats that were sent from OR to the current user.

1 Comment

I dont think this will work. By default, hasMany will try and join on chats.user_id as the default foreign key. If you chat record does not have a user_id field, it will fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.