ownerRef(); $userRef = $ownerRef; $existing = DirectConversation::owned($ownerRef) ->where('organization_id', $organization->id) ->where('type', 'dm') ->whereHas('participants', fn ($q) => $q->where('user_ref', $userRef)) ->whereHas('participants', fn ($q) => $q->where('user_ref', $otherUserRef)) ->first(); if ($existing) { return $existing; } $conversation = DirectConversation::create([ 'owner_ref' => $ownerRef, 'organization_id' => $organization->id, 'type' => 'dm', ]); foreach ([$userRef, $otherUserRef] as $ref) { DirectParticipant::create([ 'conversation_id' => $conversation->id, 'user_ref' => $ref, ]); } return $conversation; } public function postMessage(DirectConversation $conversation, User $user, string $body, ?int $parentId = null): DirectMessage { abort_unless( $conversation->participants()->where('user_ref', $user->ownerRef())->exists(), 403, ); return DirectMessage::create([ 'owner_ref' => $conversation->owner_ref, 'conversation_id' => $conversation->id, 'sender_ref' => $user->ownerRef(), 'sender_name' => $user->name, 'body' => trim($body), 'parent_id' => $parentId, ]); } }