belongsToMany(User::class, 'conversation_participants') ->withPivot('last_read_at'); } public function messages() { return $this->hasMany(Message::class)->orderBy('created_at'); } public function lastMessage() { return $this->hasOne(Message::class)->latestOfMany('created_at'); } public function unreadCountFor(int $userId): int { $pivot = $this->participants->firstWhere('id', $userId)?->pivot; $lastRead = $pivot?->last_read_at; $q = $this->messages()->where('user_id', '!=', $userId); if ($lastRead) { $q->where('created_at', '>', $lastRead); } return $q->count(); } // Find existing DM between two users or return null public static function between(int $a, int $b): ?self { return self::whereHas('participants', fn($q) => $q->where('user_id', $a)) ->whereHas('participants', fn($q) => $q->where('user_id', $b)) ->whereHas('participants', fn($q) => $q->havingRaw('COUNT(*) = 2'), null, null, fn($q) => $q->select(\DB::raw('COUNT(*)'))) ->first(); } }