references/EXAMPLE.md
PostHog Laravel Example Project
Repository: https://github.com/PostHog/context-mill Path: basics/laravel
README.md
PostHog Laravel Example
A Laravel application demonstrating PostHog integration for analytics, feature flags, and error tracking using Livewire for reactive UI components.
Features
- User registration and authentication with Livewire
- SQLite database persistence with Eloquent ORM
- User identification and property tracking
- Custom event tracking (burrito consideration tracker)
- Page view tracking (dashboard, profile)
- Feature flags with payload support
- Error tracking with manual exception capture
- Reactive UI components with Livewire
Tech Stack
- Framework: Laravel 11.x
- Reactive Components: Livewire 3.x
- Database: SQLite
- Analytics: PostHog PHP SDK
Quick Start
Note: This is a minimal implementation demonstrating PostHog integration. For a production application, you would need to install Laravel via Composer and set up additional dependencies.
Manual Setup (Demonstration)
-
Install dependencies:
composer install -
Set up environment:
cp .env.example .env # Edit .env with your PostHog project token -
Configure PostHog in
.env:POSTHOG_PROJECT_TOKEN=your_posthog_project_token POSTHOG_HOST=https://us.i.posthog.com POSTHOG_DISABLED=false -
Generate application key:
php artisan key:generate -
Create database and run migrations:
touch database/database.sqlite php artisan migrate --seed -
Start the development server:
php artisan serve -
Open http://localhost:8000 and either:
- Login with default credentials:
[email protected]/admin - Or click "Sign up here" to create a new account
- Login with default credentials:
PostHog Service
The PostHogService class (app/Services/PostHogService.php) wraps the PostHog PHP SDK and provides:
| Method | Description |
|--------|-------------|
| identify($distinctId, $properties) | Identify a user with properties |
| capture($distinctId, $event, $properties) | Capture custom events |
| captureException($exception, $distinctId) | Capture exceptions with stack traces |
| isFeatureEnabled($key, $distinctId, $properties) | Check feature flag status |
| getFeatureFlagPayload($key, $distinctId) | Get feature flag payload |
All methods check config('posthog.disabled') and return early if PostHog is disabled.
PostHog Integration Points
User Registration (app/Http/Livewire/Auth/Register.php)
New users are identified and tracked on signup:
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'user_signed_up', [
'signup_method' => 'form',
]);
User Login (app/Http/Livewire/Auth/Login.php)
Users are identified on login with their properties:
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'user_logged_in', [
'login_method' => 'password',
]);
User Logout (routes/web.php)
Logout events are tracked:
$posthog->capture($user->email, 'user_logged_out');
Page View Tracking
Dashboard and profile views are tracked (app/Http/Livewire/Dashboard.php, app/Http/Livewire/Profile.php):
$posthog->capture($user->email, 'dashboard_viewed', [
'is_staff' => $user->is_staff,
]);
$posthog->capture($user->email, 'profile_viewed');
Custom Event Tracking (app/Http/Livewire/BurritoTracker.php)
The burrito tracker demonstrates custom event capture:
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'burrito_considered', [
'total_considerations' => $this->burritoCount,
]);
Feature Flags (app/Http/Livewire/Dashboard.php)
The dashboard demonstrates feature flag checking:
$this->showNewFeature = $posthog->isFeatureEnabled(
'new-dashboard-feature',
$user->email,
$user->getPostHogProperties()
) ?? false;
$this->featureConfig = $posthog->getFeatureFlagPayload(
'new-dashboard-feature',
$user->email
);
Error Tracking
Manual exception capture is demonstrated in multiple places:
Livewire Components (app/Http/Livewire/Dashboard.php, app/Http/Livewire/Profile.php):
try {
throw new \Exception('This is a test error for PostHog tracking');
} catch (\Exception $e) {
$errorId = $posthog->captureException($e, $user->email);
$this->successMessage = "Error captured in PostHog! Error ID: {$errorId}";
}
API Endpoint (app/Http/Controllers/Api/ErrorTestController.php):
try {
throw new \Exception('Test exception from critical operation');
} catch (\Throwable $e) {
if ($shouldCapture) {
$posthog->identify($user->email, $user->getPostHogProperties());
$eventId = $posthog->captureException($e, $user->email);
return response()->json([
'error' => 'Operation failed',
'error_id' => $eventId,
'message' => "Error captured in PostHog. Reference ID: {$eventId}",
], 500);
}
}
The /api/test-error endpoint demonstrates manual exception capture. Use ?capture=true to capture in PostHog, or ?capture=false to skip tracking.
Pages
| Route | Component | PostHog Events |
|-------|-----------|----------------|
| / | Login | user_logged_in |
| /register | Register | user_signed_up |
| /dashboard | Dashboard | dashboard_viewed, feature flag checks |
| /burrito | BurritoTracker | burrito_considered |
| /profile | Profile | profile_viewed |
| /logout | (route) | user_logged_out |
Project Structure
basics/laravel/
├── app/
│ ├── Http/
│ │ ├── Controllers/
│ │ │ └── Api/
│ │ │ ├── BurritoController.php # Burrito API endpoint
│ │ │ └── ErrorTestController.php # Error testing endpoint
│ │ └── Livewire/
│ │ ├── Auth/
│ │ │ ├── Login.php # Login component
│ │ │ └── Register.php # Registration component
│ │ ├── BurritoTracker.php # Burrito tracker component
│ │ ├── Dashboard.php # Dashboard with feature flags
│ │ └── Profile.php # User profile component
│ ├── Models/
│ │ └── User.php # User model with PostHog properties
│ └── Services/
│ └── PostHogService.php # PostHog wrapper service
├── database/
│ ├── migrations/ # Database migrations
│ └── seeders/
│ └── DatabaseSeeder.php # Seeds admin user
├── resources/
│ └── views/
│ ├── components/
│ │ └── layouts/
│ │ ├── app.blade.php # Authenticated layout
│ │ └── guest.blade.php # Guest layout
│ ├── errors/
│ │ ├── 404.blade.php # Not found page
│ │ └── 500.blade.php # Server error page
│ └── livewire/
│ ├── auth/
│ │ ├── login.blade.php # Login form
│ │ └── register.blade.php # Registration form
│ ├── burrito-tracker.blade.php # Burrito tracker UI
│ ├── dashboard.blade.php # Dashboard UI
│ └── profile.blade.php # Profile UI
├── routes/
│ ├── web.php # Web routes (auth, pages)
│ └── api.php # API routes
└── config/
└── posthog.php # PostHog configuration
Development Commands
# Start development server
php artisan serve
# Run migrations
php artisan migrate
# Seed database
php artisan migrate:fresh --seed
# Clear caches
php artisan optimize:clear
.env.example
APP_NAME="PostHog Laravel Example"
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000
DB_CONNECTION=sqlite
# DB_DATABASE will use default database/database.sqlite
CACHE_DRIVER=file
CACHE_STORE=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
POSTHOG_PROJECT_TOKEN=your_posthog_project_token_here
POSTHOG_HOST=https://us.i.posthog.com
POSTHOG_DISABLED=false
app/Http/Controllers/Api/BurritoController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\PostHogService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class BurritoController extends Controller
{
public function consider(Request $request, PostHogService $posthog): JsonResponse
{
$user = Auth::user();
// Increment session counter
$burritoCount = session('burrito_count', 0) + 1;
session(['burrito_count' => $burritoCount]);
// PostHog: Track event
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'burrito_considered', [
'total_considerations' => $burritoCount,
]);
return response()->json([
'success' => true,
'count' => $burritoCount,
]);
}
}
app/Http/Controllers/Api/ErrorTestController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\PostHogService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ErrorTestController extends Controller
{
public function test(Request $request, PostHogService $posthog): JsonResponse
{
$shouldCapture = $request->query('capture', 'true') === 'true';
$user = Auth::user();
try {
throw new \Exception('Test exception from critical operation');
} catch (\Throwable $e) {
if ($shouldCapture) {
// Capture in PostHog
$posthog->identify($user->email, $user->getPostHogProperties());
$eventId = $posthog->captureException($e, $user->email);
return response()->json([
'error' => 'Operation failed',
'error_id' => $eventId,
'message' => "Error captured in PostHog. Reference ID: {$eventId}",
], 500);
}
return response()->json([
'error' => $e->getMessage(),
], 500);
}
}
}
app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
app/Http/Livewire/Auth/Login.php
<?php
namespace App\Http\Livewire\Auth;
use App\Services\PostHogService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Login extends Component
{
public string $email = '';
public string $password = '';
public bool $remember = false;
protected $rules = [
'email' => 'required|email',
'password' => 'required',
];
public function login(PostHogService $posthog)
{
$this->validate();
if (Auth::attempt(['email' => $this->email, 'password' => $this->password], $this->remember)) {
$user = Auth::user();
// PostHog: Identify and track login
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'user_logged_in', [
'login_method' => 'password',
]);
session()->regenerate();
return redirect()->intended(route('dashboard'));
}
$this->addError('email', 'Invalid credentials');
}
public function render()
{
return view('livewire.auth.login')
->layout('components.layouts.guest');
}
}
app/Http/Livewire/Auth/Register.php
<?php
namespace App\Http\Livewire\Auth;
use App\Models\User;
use App\Services\PostHogService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Register extends Component
{
public string $email = '';
public string $password = '';
public string $password_confirmation = '';
protected $rules = [
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
];
public function register(PostHogService $posthog)
{
$validated = $this->validate();
$user = User::create([
'email' => $validated['email'],
'password' => bcrypt($validated['password']),
'is_staff' => false,
]);
// PostHog: Identify new user and track signup
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'user_signed_up', [
'signup_method' => 'form',
]);
Auth::login($user);
session()->flash('success', 'Account created successfully!');
return redirect()->route('dashboard');
}
public function render()
{
return view('livewire.auth.register')
->layout('components.layouts.guest');
}
}
app/Http/Livewire/BurritoTracker.php
<?php
namespace App\Http\Livewire;
use App\Services\PostHogService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class BurritoTracker extends Component
{
public int $burritoCount = 0;
public function mount()
{
$this->burritoCount = session('burrito_count', 0);
}
public function considerBurrito(PostHogService $posthog)
{
$this->burritoCount++;
session(['burrito_count' => $this->burritoCount]);
// PostHog: Track burrito consideration
$user = Auth::user();
$posthog->identify($user->email, $user->getPostHogProperties());
$posthog->capture($user->email, 'burrito_considered', [
'total_considerations' => $this->burritoCount,
]);
$this->dispatch('burrito-considered');
}
public function render()
{
return view('livewire.burrito-tracker')
->layout('components.layouts.app');
}
}
app/Http/Livewire/Dashboard.php
<?php
namespace App\Http\Livewire;
use App\Services\PostHogService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Dashboard extends Component
{
public bool $showNewFeature = false;
public $featureConfig = null;
public ?string $errorMessage = null;
public ?string $successMessage = null;
public function mount(PostHogService $posthog)
{
$user = Auth::user();
// PostHog: Track dashboard view
$posthog->capture($user->email, 'dashboard_viewed', [
'is_staff' => $user->is_staff,
]);
// Check feature flag
$this->showNewFeature = $posthog->isFeatureEnabled(
'new-dashboard-feature',
$user->email,
$user->getPostHogProperties()
) ?? false;
// Get feature flag payload
$this->featureConfig = $posthog->getFeatureFlagPayload(
'new-dashboard-feature',
$user->email
);
}
public function testErrorWithCapture(PostHogService $posthog)
{
$user = Auth::user();
try {
// Simulate an error
throw new \Exception('This is a test error for PostHog tracking');
} catch (\Exception $e) {
// Capture the exception in PostHog
$errorId = $posthog->captureException($e, $user->email);
$this->successMessage = "Error captured in PostHog! Error ID: {$errorId}";
$this->errorMessage = null;
}
}
public function testErrorWithoutCapture()
{
try {
// Simulate an error without capturing
throw new \Exception('This error was NOT sent to PostHog');
} catch (\Exception $e) {
$this->errorMessage = "Error occurred but NOT captured in PostHog: " . $e->getMessage();
$this->successMessage = null;
}
}
public function render()
{
return view('livewire.dashboard')
->layout('components.layouts.app');
}
}
app/Http/Livewire/Profile.php
<?php
namespace App\Http\Livewire;
use App\Services\PostHogService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Profile extends Component
{
public ?string $errorMessage = null;
public ?string $successMessage = null;
public function mount(PostHogService $posthog)
{
$user = Auth::user();
// PostHog: Track profile view
$posthog->capture($user->email, 'profile_viewed');
}
public function testErrorWithCapture(PostHogService $posthog)
{
$user = Auth::user();
try {
// Simulate an error
throw new \Exception('This is a test error for PostHog tracking');
} catch (\Exception $e) {
// Capture the exception in PostHog
$errorId = $posthog->captureException($e, $user->email);
$this->successMessage = "Error captured in PostHog! Error ID: {$errorId}";
$this->errorMessage = null;
}
}
public function testErrorWithoutCapture()
{
try {
// Simulate an error without capturing
throw new \Exception('This error was NOT sent to PostHog');
} catch (\Exception $e) {
$this->errorMessage = "Error occurred but NOT captured in PostHog: " . $e->getMessage();
$this->successMessage = null;
}
}
public function render()
{
return view('livewire.profile')
->layout('components.layouts.app');
}
}
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $fillable = [
'email',
'password',
'is_staff',
];
protected $hidden = [
'password',
'remember_token',
];
protected function casts(): array
{
return [
'password' => 'hashed',
'is_staff' => 'boolean',
];
}
/**
* Get PostHog person properties for this user.
*/
public function getPostHogProperties(): array
{
return [
'email' => $this->email,
'is_staff' => $this->is_staff,
'date_joined' => $this->created_at->toISOString(),
];
}
}
app/Services/PostHogService.php
<?php
namespace App\Services;
use PostHog\PostHog;
use Illuminate\Support\Facades\Auth;
class PostHogService
{
protected static $initialized = false;
public function __construct()
{
if (config('posthog.disabled')) {
return;
}
// Initialize PostHog once
if (!self::$initialized) {
PostHog::init(
config('posthog.api_key'),
[
'host' => config('posthog.host'),
'debug' => config('posthog.debug'),
]
);
self::$initialized = true;
}
}
public function identify(string $distinctId, array $properties = []): void
{
if (config('posthog.disabled')) {
return;
}
PostHog::identify([
'distinctId' => $distinctId,
'properties' => $properties,
]);
}
public function capture(string $distinctId, string $event, array $properties = []): void
{
if (config('posthog.disabled')) {
return;
}
PostHog::capture([
'distinctId' => $distinctId,
'event' => $event,
'properties' => $properties,
]);
}
public function captureException(\Throwable $exception, ?string $distinctId = null): ?string
{
if (config('posthog.disabled')) {
return null;
}
$distinctId = $distinctId ?? Auth::user()?->email ?? 'anonymous';
$eventId = uniqid('error_', true);
$this->capture($distinctId, '$exception', [
'error_id' => $eventId,
'exception_type' => get_class($exception),
'exception_message' => $exception->getMessage(),
'exception_file' => $exception->getFile(),
'exception_line' => $exception->getLine(),
'stack_trace' => $exception->getTraceAsString(),
]);
return $eventId;
}
public function isFeatureEnabled(string $key, string $distinctId, array $properties = []): ?bool
{
if (config('posthog.disabled')) {
return false;
}
return PostHog::isFeatureEnabled($key, $distinctId, $properties);
}
public function getFeatureFlagPayload(string $key, string $distinctId)
{
if (config('posthog.disabled')) {
return null;
}
return PostHog::getFeatureFlagPayload($key, $distinctId);
}
}
artisan
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
$kernel->terminate($input, $status);
exit($status);
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
bootstrap/cache/packages.php
<?php return array (
'livewire/livewire' =>
array (
'aliases' =>
array (
'Livewire' => 'Livewire\\Livewire',
),
'providers' =>
array (
0 => 'Livewire\\LivewireServiceProvider',
),
),
'nesbot/carbon' =>
array (
'providers' =>
array (
0 => 'Carbon\\Laravel\\ServiceProvider',
),
),
'nunomaduro/termwind' =>
array (
'providers' =>
array (
0 => 'Termwind\\Laravel\\TermwindServiceProvider',
),
),
);
bootstrap/cache/services.php
<?php return array (
'providers' =>
array (
0 => 'Illuminate\\Auth\\AuthServiceProvider',
1 => 'Illuminate\\Broadcasting\\BroadcastServiceProvider',
2 => 'Illuminate\\Bus\\BusServiceProvider',
3 => 'Illuminate\\Cache\\CacheServiceProvider',
4 => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
5 => 'Illuminate\\Cookie\\CookieServiceProvider',
6 => 'Illuminate\\Database\\DatabaseServiceProvider',
7 => 'Illuminate\\Encryption\\EncryptionServiceProvider',
8 => 'Illuminate\\Filesystem\\FilesystemServiceProvider',
9 => 'Illuminate\\Foundation\\Providers\\FoundationServiceProvider',
10 => 'Illuminate\\Hashing\\HashServiceProvider',
11 => 'Illuminate\\Mail\\MailServiceProvider',
12 => 'Illuminate\\Notifications\\NotificationServicePr