Laravel
Contents
You can integrate PostHog with Laravel using the experimental Laravel SDK or the PHP SDK with manual instrumentation. Both approaches are supported. The Laravel SDK builds on the PHP SDK and adds automatic request context, exception reporting, and worker lifecycle management.
Laravel SDK (experimental)
Experimental: The Laravel SDK is under active development, and its API may change. If you prefer to instrument your application yourself, the manual PHP SDK setup remains supported.
The PostHog Laravel SDK supports Laravel 12 and 13. It requires PHP 8.2 or later (PHP 8.3 or later for Laravel 13).
Installation
Install posthog/posthog-laravel and publish its configuration:
Add your project token and ingestion host to your server's .env:
Laravel's package discovery registers the service provider and facade automatically. If discovery is disabled, register PostHog\Laravel\PostHogServiceProvider manually. No PHP SDK initialization or custom middleware is needed.
Configure the SDK in config/posthog.php. It's enabled by default; set POSTHOG_ENABLED=false to disable it.
For browser events and session replay, install the JavaScript SDK separately.
SDK configuration
From version 0.2.0, set these optional variables in your server's .env to tune delivery and feature-flag requests:
| Variable | Default |
|---|---|
POSTHOG_TIMEOUT_MS | 10000 milliseconds (cURL delivery and SDK HTTP requests) |
POSTHOG_SOCKET_TIMEOUT_SECONDS | 5 seconds (socket delivery only) |
POSTHOG_BATCH_SIZE | 100 events |
POSTHOG_MAX_QUEUE_SIZE | 10000 buffered events |
POSTHOG_FLUSH_INTERVAL_SECONDS | 5 seconds |
POSTHOG_COMPRESS_REQUEST | false |
POSTHOG_CONSUMER | lib_curl |
POSTHOG_FF_REQUEST_TIMEOUT_MS | 3000 milliseconds (remote flag evaluation) |
POSTHOG_FF_REQUEST_MAX_RETRIES | 1 retry |
The flush interval is checked when events are captured, not by a background timer. Lifecycle flushes still apply.
If you already published config/posthog.php, copy the environment mappings and conversion helpers from the package configuration. Package updates and posthog:install don't overwrite your existing config. After configuration changes, run php artisan config:cache if you cache configuration, and restart long-running workers.
Capturing events and identifying users
Use the Laravel facade, not the PHP SDK's PostHog\PostHog class:
The SDK uses the authenticated user's ID automatically, or you can pass a distinct ID explicitly as shown above. Without an identity, each event gets a new random ID without a person profile; these IDs don't identify returning visitors.
To link browser sessions to backend events, configure the JavaScript SDK's tracing headers. These headers are untrusted analytics input, not authentication. Pass an authenticated identity explicitly for security-sensitive events or flag decisions.
The SDK doesn't collect request bodies, query strings, or email by default. Check your own event properties and exception messages for sensitive data.
Request IP addresses
From version 0.2.0, events include $ip from Laravel's request()->ip(). Configure Laravel's trusted proxies when running behind a proxy or load balancer. Set POSTHOG_CAPTURE_IP=false to disable automatic IP collection; explicitly supplied IPs are unchanged.
GeoIP enrichment is separate and remains disabled by default. To enable it, set "disableGeoip" => false in the sdk section of config/posthog.php.
Feature flags
Evaluate flags using the current request identity, or pass a distinct ID explicitly:
You can omit distinctId to use the current request identity. Without an identity, flag evaluation returns an empty result.
For local evaluation, set POSTHOG_SECRET_KEY to your feature flags secure API key. Keep it on the server. In production, enable flag_cache.enabled and select a shared Laravel cache store with flag_cache.store in config/posthog.php.
Laravel Pennant
The SDK includes an optional read-only Pennant store. Install Pennant and select the PostHog store:
Read flags using their PostHog keys:
Pennant uses the authenticated user by default, or an explicit scope as shown above. The store is read-only: create and manage flags in PostHog, not through Pennant write operations. You don't need a Pennant migration.
Capturing exceptions
The SDK automatically captures exceptions reported through Laravel's reportable exception path. It respects dontReport and callbacks that stop reporting. Set capture_exceptions to false in config/posthog.php to disable automatic reporting.
To capture a handled exception explicitly:
Don't add the manual PHP SDK report callback below when using the Laravel SDK, as this can report exceptions twice.
Optional server event collectors
All automatic server event collectors are off by default. They capture Laravel lifecycle events, not browser clicks or $autocapture events.
Publish the collector configuration:
Enable only the collectors you need in config/posthog-autocapture.php. For example, update the auth section to capture registrations, logins, and logouts:
Set requests.enabled to true for laravel_request events with route, method, status code, and duration. Keep the generated health-check and static-asset exclusions. Other collectors cover model changes, mapped domain events, jobs, commands, and scheduled tasks. Model attributes and domain-event properties must be explicitly allowlisted.
Server $pageview events are a separate opt-in through pageviews.enabled. Leave them disabled if your browser SDK already captures pageviews to avoid duplicates.
Blade flag conditionals
Set blade.enabled to true in config/posthog-autocapture.php to enable the optional Blade conditional:
This uses evaluateFlags()->isEnabled() with the current analytics context. Repeated checks share the evaluation snapshot and exposure deduplication. Disabled or unavailable flags select the @else branch. This is a presentation helper, not authorization.
Queue workers and Octane
The SDK automatically flushes events and clears context between requests, queue jobs, console commands, and sequential Octane lifecycles. Identity and session context propagate to jobs by default; set queue_context to false to disable this.
Don't store scoped PostHog services in application singletons. Overlapping Swoole coroutines sharing one Laravel container aren't supported.
Queued event delivery
From version 0.3.0, you can send event batches through Laravel queue workers instead of the current PHP process. To enable queued delivery, configure:
Start a worker for that connection and queue:
Set retry_after to 240 seconds for the Redis connection in config/queue.php. The worker timeout must cover all SDK HTTP attempts and backoff, and retry_after must exceed the worker timeout. Increase both if you increase SDK timeouts or retry backoff.
Producers and workers need the same project configuration and valid APP_KEY, which Laravel uses to encrypt delivery jobs. If you already published config/posthog.php, add the package's new laravel_queue section. Rebuild cached configuration and restart workers after changes.
Omit the connection and queue name to use Laravel's defaults. Use a non-sync connection for background delivery. SDK batching still applies, and a successful flush() confirms queue handoff, not receipt by PostHog. Feature-flag requests remain synchronous. This setting is separate from queue_context, which passes analytics context to your application's jobs.
Testing and diagnostics
Use the fake to test instrumentation without sending events:
Run php artisan posthog:doctor to validate local configuration without sending a diagnostic event. To send a test event explicitly, run php artisan posthog:test --send.
Manual setup with the PHP SDK
Using the PHP SDK directly remains supported. Use this approach if you want to manage initialization, request context, exception reporting, and flushing yourself. The examples below use PostHog\PostHog, not the Laravel facade. Don't combine this setup with the Laravel SDK's automatic integration.
The wizard installs the PHP SDK, not the experimental Laravel SDK.
Install with the wizard
Run this command in your project directory to add PostHog to your Laravel project. The wizard detects your framework, installs the SDK, and sets up your first events.
Or set it up manually by following the rest of this guide.
Initialize the PHP SDK
Install the PHP SDK as described in the PHP installation guide, then add your project token and host to .env:
Add PostHog to Laravel's services config:
Initialize PostHog in the boot method of app/Providers/AppServiceProvider.php:
Request context middleware
Client SDKs such as PostHog JS can send tracing headers to your Laravel backend. Configure tracing_headers for your Laravel backend hostname so browser requests include the session and distinct ID headers.
The PHP SDK can read X-PostHog-Distinct-Id and X-PostHog-Session-Id headers and apply them to events captured during the request. Tracing headers are client-controlled analytics context, not authentication or authorization. For security-sensitive server-side events or decisions, pass an authenticated distinctId explicitly, such as auth()->id(). For the lower-level context APIs, see the PHP request context docs.
Add middleware like this:
Register this middleware using your Laravel version's normal middleware registration.
Error tracking in Laravel
The PHP SDK supports error tracking, but Laravel handles most request exceptions before they become uncaught PHP exceptions. Capture Laravel-reported exceptions explicitly.
In Laravel 11 and later, add a report callback in bootstrap/app.php:
For older Laravel versions, call PostHog::captureException() from your exception handler's report method.
Long-running processes
In normal PHP request lifecycles, queued events flush when the client is destroyed. In long-running Laravel processes such as queue workers, Horizon, or Octane, call PostHog::flush() after capturing important events or at the end of a job/request.
If you prefer immediate delivery in queue workers, configure the PHP SDK with batch_size set to 1 for those workers:
Next steps
See the PHP SDK docs for usage examples and the full API reference.





