Reputation: 1075
I'm currently working on a private messaging system in Laravel.
I am trying to display a list of message threads in a user's inbox. This works similar to how an instant messaging system displays messages whereby all messages between 2 users are stored in a single thread.
The issue I am having is that I have multiple message types: "Message" and "Task". In the "Message" inbox, I only want to display message threads with the thread type as "Message". To do this I am using the following code in my controller:
$messageThreads = Thread::where('type', 'Message')
->where('sender_id', $user)
->orWhere('recipient_id', $user)
->get()
->sortByDesc('updated_at');
This however isn't working and is still retrieving message threads where the type is "Task" instead of being limited to "Message"
I have also tried:
$messageThreads = Thread::where('sender_id', $user)
->orWhere('recipient_id', $user)
->where('type', 'Message')
->get()
->sortByDesc('updated_at');
But this also returned the same result.
The interesting thing is if I just leave it as
$messageThreads = Thread::where('type', 'Message')
It will only retrieve messages with the type "Message". It is only when I add the other "where" clauses, that it stops working properly.
Upvotes: 0
Views: 65
Reputation: 9329
As mentioned you likely need to group your where clauses:
Thread::where('type','Message')
->where(function($query)
{
$query->where('sender_id',$user)
->orWhere('recipient_id',$user);
})->get();
The reason is that you are looking for a Thread
where
its type
is Message
orWhere
its recipient_id
is the $user
. Their may be messages which aren't of type message, but do have the user as a recipient ID.
https://laravel.com/docs/5.6/queries#parameter-grouping
Upvotes: 2