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 ?
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.
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.