> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Laravel (PHP) Canonical URL: https://posthog.com/docs/libraries/laravel-php > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). ## On this page - [Laravel SDK (experimental)](#laravel-sdk-experimental) - [Manual setup with the PHP SDK](#manual-setup-with-the-php-sdk) - [Install with the wizard](#install-with-the-wizard) - [Next steps](#next-steps) You can integrate PostHog with Laravel using the [experimental Laravel SDK](#laravel-sdk-experimental) or the [PHP SDK with manual instrumentation](#manual-setup-with-the-php-sdk). Both approaches are supported. The Laravel SDK builds on the PHP SDK and adds automatic request context, exception reporting, and worker lifecycle management. Using [Laravel Rust](https://laravel.com/rust)? See the [Laravel Rust guide](https://posthog.com/docs/libraries/laravel-rs.md) for the Rust SDK's `laravel` feature. ## 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](#manual-setup-with-the-php-sdk) remains supported. The [PostHog Laravel SDK](https://github.com/PostHog/posthog-laravel) 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`](https://packagist.org/packages/posthog/posthog-laravel) and publish its configuration: ```bash composer require "posthog/posthog-laravel:^0.4" php artisan posthog:install ``` Add your project token and ingestion host to your server's `.env`: .env ```bash POSTHOG_PROJECT_TOKEN= POSTHOG_HOST=https://us.i.posthog.com ``` 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. To turn PostHog off for part of the app, call `PostHog::setDisabled(true)`, and call `PostHog::setDisabled(false)` to turn it back on. This lasts for the current request, job, or command, and the next one starts from configuration again. While disabled, nothing is captured, autocapture and context collection stop, and flag evaluation returns defaults. Events already queued are still delivered. `PostHog::isDisabled()` reports the current state. To start each request, job, and command disabled, set `POSTHOG_DISABLED=true`, which sets `sdk.disabled` in `config/posthog.php`. `setDisabled(false)` can't turn on a client that `POSTHOG_ENABLED=false` or a missing project token turned off. For browser events and session replay, install the [JavaScript SDK](https://posthog.com/docs/libraries/js.md) 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](https://github.com/PostHog/posthog-php/blob/main/packages/laravel/config/posthog.php). 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: ```php use PostHog\Laravel\Facades\PostHog; PostHog::capture("checkout_completed", ["items" => 2]); PostHog::capture("import_completed", ["rows" => 42], "account-123"); PostHog::identify([ "distinctId" => "account-123", "properties" => ["plan" => "paid"], ]); ``` 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](https://posthog.com/docs/libraries/js/config.md#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](https://laravel.com/docs/requests#configuring-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: ```php use PostHog\Laravel\Facades\PostHog; $flags = PostHog::evaluateFlags(distinctId: "account-123"); $isEnabled = $flags->isEnabled("new-checkout"); $variant = $flags->getFlag("checkout-layout"); $payload = $flags->getFlagPayload("checkout-layout"); ``` You can omit `distinctId` to use the current request identity. Without an identity, flag evaluation returns an empty result. For [local evaluation](https://posthog.com/docs/feature-flags/local-evaluation.md), 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`. #### Remote config To read the payload of a [remote config](https://posthog.com/docs/feature-flags/remote-config.md) flag, call `getRemoteConfigPayload` with the flag key. It needs no distinct ID, and it requires `POSTHOG_SECRET_KEY` and `posthog/posthog-laravel` 0.5.0 or later: ```php use PostHog\Laravel\Facades\PostHog; $config = PostHog::getRemoteConfigPayload("landing-page-config"); ``` ### Laravel Pennant The SDK includes an optional read-only Pennant store. Install Pennant and select the PostHog store: ```bash composer require laravel/pennant:^1.26 ``` .env ```bash PENNANT_STORE=posthog ``` Read flags using their PostHog keys: ```php use Laravel\Pennant\Feature; $isEnabled = Feature::for("account-123")->active("new-checkout"); $variant = Feature::for("account-123")->value("checkout-layout"); ``` 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: ```php use PostHog\Laravel\Facades\PostHog; PostHog::captureException($exception, properties: ["component" => "import"]); ``` 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: ```bash php artisan vendor:publish --tag=posthog-autocapture-config ``` Enable only the collectors you need in `config/posthog-autocapture.php`. For example, update the `auth` section to capture registrations, logins, and logouts: config/posthog-autocapture.php ```php "auth" => [ "enabled" => true, "events" => ["registered", "login", "logout"], ], ``` 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: ```blade @posthogFeature("new-checkout") @else @endposthogFeature ``` 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: .env ```bash POSTHOG_LARAVEL_QUEUE_ENABLED=true POSTHOG_LARAVEL_QUEUE_CONNECTION=redis POSTHOG_LARAVEL_QUEUE_NAME=posthog ``` Start a worker for that connection and queue: ```bash php artisan queue:work redis --queue=posthog --tries=3 --backoff=10 --timeout=180 ``` 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: ```php use PostHog\Laravel\Facades\PostHog; $fake = PostHog::fake(); PostHog::capture("checkout_completed", ["items" => 2], "account-123"); $fake->assertCaptured("checkout_completed"); $fake->assertCapturedCount(1); ``` The fake follows `PostHog::setDisabled()` and `posthog.sdk.disabled`. While disabled, it records nothing, so `assertNotCaptured()` and `assertNothingCaptured()` pass without checking anything. `POSTHOG_ENABLED=false` does not affect the fake. 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](https://posthog.com/docs/libraries/php.md) 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. `npx @posthog/wizard` 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](https://posthog.com/docs/libraries/php.md#installation): ```bash composer require "posthog/posthog-php:^4.0" ``` Then add your project token and host to `.env`: .env ```bash POSTHOG_PROJECT_TOKEN= POSTHOG_HOST=https://us.i.posthog.com ``` Add PostHog to Laravel's services config: config/services.php ```php 'posthog' => [ 'project_token' => env('POSTHOG_PROJECT_TOKEN'), 'host' => env('POSTHOG_HOST', 'https://us.i.posthog.com'), ], ``` Initialize PostHog in the `boot` method of `app/Providers/AppServiceProvider.php`: app/Providers/AppServiceProvider.php ```php config('services.posthog.host'), ] ); } } ``` ### Request context middleware Client SDKs such as [PostHog JS](https://posthog.com/docs/libraries/js.md) can send tracing headers to your Laravel backend. Configure [`tracing_headers`](https://posthog.com/docs/libraries/js/config.md#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](https://posthog.com/docs/libraries/php.md#request-context). Add middleware like this: app/Http/Middleware/PostHogRequestContext.php ```php headers->all()); $context['properties'] = array_merge( $context['properties'] ?? [], array_filter([ '$current_url' => $request->fullUrl(), '$request_method' => $request->method(), '$request_path' => $request->getPathInfo(), '$user_agent' => $request->userAgent(), '$ip' => $request->ip(), ], static fn ($value): bool => $value !== null && $value !== '') ); return PostHog::withContext( $context, static fn (): Response => $next($request), ['fresh' => true] ); } } ``` Register this middleware using your Laravel version's normal middleware registration. ### Error tracking in Laravel The PHP SDK supports [error tracking](https://posthog.com/docs/libraries/php.md#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`: bootstrap/app.php ```php use Illuminate\Foundation\Configuration\Exceptions; use PostHog\PostHog; use Throwable; ->withExceptions(function (Exceptions $exceptions): void { $exceptions->report(function (Throwable $e): void { if (! config('services.posthog.project_token')) { return; } PostHog::captureException( $e, auth()->id() !== null ? (string) auth()->id() : null, [ '$current_url' => request()->fullUrl(), '$request_method' => request()->method(), ] ); }); }) ``` 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: ```php PostHog::init( config('services.posthog.project_token'), [ 'host' => config('services.posthog.host'), 'batch_size' => 1, ] ); ``` ## Next steps See the [PHP SDK docs](https://posthog.com/docs/libraries/php.md) for usage examples and the full API reference.