AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-product-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 62

references/EXAMPLE-laravel.md

PostHog laravel Example Project

Repository: https://github.com/PostHog/context-mill Path: example-apps/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)

  1. Install dependencies:

    composer install
    
  2. Set up environment:

    cp .env.example .env
    # Edit .env with your PostHog project token
    
  3. Configure PostHog in .env:

    POSTHOG_PROJECT_TOKEN=your_posthog_project_token
    POSTHOG_HOST=https://us.i.posthog.com
    POSTHOG_DISABLED=false
    
  4. Generate application key:

    php artisan key:generate
    
  5. Create database and run migrations:

    touch database/database.sqlite
    php artisan migrate --seed
    
  6. Start the development server:

    php artisan serve
    
  7. Open http://localhost:8000 and either:

    • Login with default credentials: [email protected] / admin
    • Or click "Sign up here" to create a new account

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

example-apps/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);

        PostHog::captureException($exception, $distinctId, [
            'error_id' => $eventId,
        ]);

        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();


config/app.php

<?php

return [
    'name' => env('APP_NAME', 'PostHog Laravel Example'),
    'env' => env('APP_ENV', 'production'),
    'debug' => (bool) env('APP_DEBUG', false),
    'url' => env('APP_URL', 'http://localhost'),
    'timezone' => 'UTC',
    'locale' => 'en',
    'fallback_locale' => 'en',
    'key' => env('APP_KEY'),
    'cipher' => 'AES-256-CBC',

    'providers' => [
        // Laravel Framework Service Providers
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::cl