1đź‘Ť
âś…
If I’ve understood the question right you’re looking for the messages belonging to the conversation between two users, so what you’re looking for should be following:
$loggedInUserId = 2;
$contactUserId = 3;
$messages = Message::query()
->where(function ($query) use ($loggedInUserId, $contactUserId) {
$query->where('sender_id', $loggedInUserId)
->where('recipient_id', $contactUserId);
})
->orWhere(function ($query) use ($loggedInUserId, $contactUserId) {
$query->where('recipient_id', $loggedInUserId)
->where('sender_id', $contactUserId);
})
->with('owner')
->orderBy('created_at', 'desc')
->get();
Also, if you’re heavily relying on having to track “conversations” between two or more users you might think to aggregate them as threads.
Source:stackexchange.com