Laravel
Contents
PostHog integrates with Laravel through the PostHog PHP SDK. This page covers Laravel-specific setup. For SDK features such as event capture, identifying users, feature flags, group analytics, and configuration options, see the PHP SDK docs.
Installation
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. The PHP SDK can read X-PostHog-Distinct-Id and X-PostHog-Session-Id headers and apply them to events captured during the request. 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.
Next steps
See the PHP SDK docs for usage examples and the full API reference.