From 42af4be150af2a12e3f378ca976254acecfe9901 Mon Sep 17 00:00:00 2001 From: Joseph Szobody Date: Fri, 20 Feb 2026 10:59:58 -0500 Subject: [PATCH] Move session ID hash into getAnonymousId Session-based users are still anonymous (not authenticated), so the hashed session ID belongs in getAnonymousId() alongside the random string fallback. getUserId() now simply checks auth or anonymous. --- README.md | 5 ++--- src/Drivers/AbstractDriver.php | 12 +++++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index dd11dc0..6159f76 100644 --- a/README.md +++ b/README.md @@ -276,11 +276,10 @@ The closure will be called fresh each time a metric is formatted. This also work ## User ID resolution -Drivers automatically resolve the current user ID using the following strategy: +Drivers automatically resolve the current user ID via `getUserId()`: 1. If a user is authenticated: `auth()->id()` -2. If a session is active: a hashed session ID -3. Otherwise: a random string (stable for the lifetime of the process) +2. Otherwise: `getAnonymousId()`, which returns a hashed session ID if a session is active, or a random string (stable for the lifetime of the process) This is used by the PostHog driver as the `distinctId`, and is available to any driver via `$driver->getUserId()`. diff --git a/src/Drivers/AbstractDriver.php b/src/Drivers/AbstractDriver.php index b342be9..c654373 100644 --- a/src/Drivers/AbstractDriver.php +++ b/src/Drivers/AbstractDriver.php @@ -79,15 +79,17 @@ public function getUserId(): mixed return call_user_func($this->userIdResolver, $this); } - return match(true) { - auth()->check() => auth()->id(), - session()->isStarted() => sha1(session()->getId()), - default => $this->getAnonymousId() - }; + return auth()->check() + ? auth()->id() + : $this->getAnonymousId(); } public function getAnonymousId(): string { + if (session()->isStarted()) { + return sha1(session()->getId()); + } + static $anonymousId = null; return $anonymousId ??= Str::random();