AGENTIC MEMORY

Skills

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

← Back to Skills

integration-laravel

PostHog integration for Laravel applications

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--integration-laravel 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 · 8

references/EXAMPLE.md · 48000

turn [ 'driver' => env('SESSION_DRIVER', 'file'), 'lifetime' => env('SESSION_LIFETIME', 120), 'expire_on_close' => false, 'encrypt' => false, 'files' => storage_path('framework/sessions'), 'connection' => null, 'table' => 'sessions', 'store' => null, 'lottery' => [2, 100], 'cookie' => env('SESSION_COOKIE', 'laravel_session'), 'path' => '/', 'domain' => env('SESSION_DOMAIN'), 'secure' => env('SESSION_SECURE_COOKIE'), 'http_only' => true, 'same_site' => 'lax', ];


---

## database/migrations/2024_01_01_000000_create_users_table.php

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();
            $table->string('password');
            $table->boolean('is_staff')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};


database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        User::firstOrCreate(
            ['email' => '[email protected]'],
            [
                'password' => bcrypt('admin'),
                'is_staff' => true,
            ]
        );
    }
}


IMPLEMENTATION.md

Laravel PostHog Example - Implementation Summary

This document summarizes the implementation of the Laravel PostHog example application, ported from the Flask version.

✅ Completed Implementation

Core Application Structure

Models & Database

  • ✅ User model with PostHog properties helper method
  • ✅ User migration with is_staff field
  • ✅ Database seeder for default admin user
  • ✅ SQLite database configuration

PostHog Integration

  • ✅ PostHog configuration file (config/posthog.php)
  • ✅ PostHogService class with all core methods:
    • identify() - User identification
    • capture() - Event tracking
    • captureException() - Error tracking
    • isFeatureEnabled() - Feature flag checking
    • getFeatureFlagPayload() - Feature flag payload retrieval

Authentication (Livewire Components)

  • ✅ Login component with PostHog tracking
  • ✅ Register component with PostHog tracking
  • ✅ Logout route with PostHog tracking

Core Features (Livewire Components)

  • ✅ Dashboard - Feature flag demonstration
  • ✅ Burrito Tracker - Custom event tracking
  • ✅ Profile - Error tracking demonstration

API Controllers

  • ✅ BurritoController - API endpoint for burrito tracking
  • ✅ ErrorTestController - Manual error capture demonstration

Views & Layouts

  • ✅ App layout (authenticated users)
  • ✅ Guest layout (unauthenticated users)
  • ✅ All Livewire view files with inline styling
  • ✅ Error pages (404, 500)

Routes

  • ✅ Web routes (authentication, dashboard, burrito, profile, logout)
  • ✅ API routes (burrito tracking, error testing)

Configuration

  • ✅ Environment example file
  • ✅ Composer.json with dependencies
  • ✅ Laravel config files (app, auth, database, session)
  • ✅ .gitignore

Documentation

  • ✅ Comprehensive README
  • ✅ Implementation plan (php-plan.md)

📋 Features Implemented

1. User Authentication

  • Login with PostHog identification
  • Registration with PostHog tracking
  • Logout with event capture
  • Session management

2. PostHog Analytics

  • User identification on login/signup
  • Person properties (email, is_staff, date_joined)
  • Custom event tracking (burrito considerations)
  • Dashboard views tracking

3. Feature Flags

  • Feature flag checking (new-dashboard-feature)
  • Feature flag payload retrieval
  • Conditional UI rendering based on flags

4. Error Tracking

  • Manual exception capture
  • Error ID generation
  • Test endpoint with optional capture (?capture=true/false)

5. UI/UX

  • Responsive layouts
  • Flash messages for user feedback
  • Livewire reactivity for burrito counter
  • Loading states on buttons

🎯 PostHog Integration Points

| Feature | Location | PostHog Method | |---------|----------|----------------| | User Login | Login.php:23-27 | identify() + capture() | | User Signup | Register.php:29-32 | identify() + capture() | | User Logout | web.php:25 | capture() | | Dashboard View | Dashboard.php:18 | capture() | | Feature Flag Check | Dashboard.php:21-25 | isFeatureEnabled() | | Feature Flag Payload | Dashboard.php:28-31 | getFeatureFlagPayload() | | Burrito Tracking | BurritoTracker.php:22-24 | identify() + capture() | | Profile View | Profile.php:14 | capture() | | Error Capture | ErrorTestController.php:22-24 | identify() + captureException() |

📁 File Structure

basics/laravel/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── Controller.php
│   │   │   └── Api/
│   │   │       ├── BurritoController.php
│   │   │       └── ErrorTestController.php
│   │   └── Livewire/
│   │       ├── Auth/
│   │       │   ├── Login.php
│   │       │   └── Register.php
│   │       ├── Dashboard.php
│   │       ├── BurritoTracker.php
│   │       └── Profile.php
│   ├── Models/
│   │   └── User.php
│   └── Services/
│       └── PostHogService.php
├── config/
│   ├── app.php
│   ├── auth.php
│   ├── database.php
│   ├── posthog.php
│   └── session.php
├── database/
│   ├── migrations/
│   │   └── 2024_01_01_000000_create_users_table.php
│   └── seeders/
│       └── DatabaseSeeder.php
├── resources/
│   └── views/
│       ├── components/
│       │   └── layouts/
│       │       ├── app.blade.php
│       │       └── guest.blade.php
│       ├── livewire/
│       │   ├── auth/
│       │   │   ├── login.blade.php
│       │   │   └── register.blade.php
│       │   ├── dashboard.blade.php
│       │   ├── burrito-tracker.blade.php
│       │   └── profile.blade.php
│       └── errors/
│           ├── 404.blade.php
│           └── 500.blade.php
├── routes/
│   ├── api.php
│   └── web.php
├── .env.example
├── .gitignore
├── composer.json
├── IMPLEMENTATION.md
└── README.md

🔄 Flask to Laravel Mapping

| Flask Component | Laravel Equivalent | |----------------|-------------------| | Flask-Login | Laravel Auth + Livewire | | Flask-SQLAlchemy | Eloquent ORM | | Jinja2 Templates | Blade Templates + Livewire | | Blueprint routes | Route definitions | | @app.route decorators | Route::get/post | | session | session() helper | | flash() | session()->flash() | | @login_required | Route::middleware('auth') | | request.form | Livewire properties | | render_template() | view() or Livewire render() | | jsonify() | response()->json() | | SQLAlchemy models | Eloquent models |

🚀 Next Steps for Production

To make this a production-ready application:

  1. Install via Composer: Run full Laravel installation
  2. Environment: Generate APP_KEY with php artisan key:generate
  3. Database: Run migrations with php artisan migrate --seed
  4. Assets: Set up Vite for asset compilation
  5. Middleware: Add CSRF protection middleware
  6. Validation: Add form request classes
  7. Testing: Implement PHPUnit tests
  8. Caching: Configure Redis/Memcached
  9. Queue: Set up queue workers for PostHog events
  10. Deployment: Configure for production server

📝 Notes

  • This implementation uses inline CSS (matching Flask example) instead of Tailwind compilation
  • Livewire provides reactivity without separate JavaScript files
  • PostHog service is dependency-injected into components/controllers
  • Manual error capture pattern matches Flask implementation
  • Session-based burrito counter (same as Flask)
  • Default admin account: [email protected] / admin

🎓 Learning Resources


Implementation Date: January 2026 Laravel Version: 11.x Livewire Version: 3.x PostHog PHP SDK: 3.x


public/index.php

<?php

use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

// Suppress PHP 8.5 deprecation warnings for development
error_reporting(E_ALL & ~E_DEPRECATED);

// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
    require $maintenance;
}

// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';

// Bootstrap Laravel and handle the request...
(require_once __DIR__.'/../bootstrap/app.php')
    ->handleRequest(Request::capture());


resources/views/components/layouts/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ $title ?? 'PostHog Laravel Example' }}</title>

    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            line-height: 1.6;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        nav {
            background: #1d4ed8;
            padding: 15px 20px;
            margin-bottom: 30px;
        }
        nav a {
            color: white;
            text-decoration: none;
            margin-right: 20px;
        }
        nav a:hover {
            text-decoration: underline;
        }
        .nav-right {
            float: right;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1, h2, h3 {
            margin-bottom: 15px;
            color: #1d4ed8;
        }
        button, .btn {
            background: #1d4ed8;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            display: inline-block;
            text-decoration: none;
        }
        button:hover, .btn:hover {
            background: #1e40af;
        }
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        button.danger, .btn-danger {
            background: #dc2626;
        }
        button.danger:hover, .btn-danger:hover {
            background: #b91c1c;
        }
        input {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .message-error {
            background: #fee2e2;
            color: #dc2626;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .message-success {
            background: #d1fae5;
            color: #059669;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .feature-flag {
            background: #fef3c7;
            border: 2px dashed #f59e0b;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        code {
            background: #f3f4f6;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }
        pre {
            background: #1e293b;
            color: #e2e8f0;
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
            font-size: 13px;
        }
        .count {
            font-size: 48px;
            font-weight: bold;
            color: #1d4ed8;
            text-align: center;
            padding: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 16px 0;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        th {
            background: #f8fafc;
            font-weight: 600;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        .text-sm {
            font-size: 14px;
        }
        .text-gray {
            color: #666;
        }
        .mb-4 {
            margin-bottom: 16px;
        }
    </style>
    @livewireStyles
</head>
<body>
    @auth
    <nav>
        <a href="{{ route('dashboard') }}">Dashboard</a>
        <a href="{{ route('burrito') }}">Burrito</a>
        <a href="{{ route('profile') }}">Profile</a>
        <span class="nav-right">
            <span style="margin-right: 15px;">{{ auth()->user()->email }}</span>
            <form method="POST" action="{{ route('logout') }}" style="display: inline;">
                @csrf
                <button type="submit" style="background: none; padding: 0; color: white; text-decoration: underline;">Logout</button>
            </form>
        </span>
    </nav>
    @endauth

    <div class="container">
        @if (session('success'))
            <div class="message-success">
                {{ session('success') }}
            </div>
        @endif

        @if (session('error'))
            <div class="message-error">
                {{ session('error') }}
            </div>
        @endif

        {{ $slot }}
    </div>

    @livewireScripts
</body>
</html>


resources/views/components/layouts/guest.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ $title ?? 'PostHog Laravel Example' }}</title>

    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            line-height: 1.6;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1, h2, h3 {
            margin-bottom: 15px;
            color: #1d4ed8;
        }
        button, .btn {
            background: #1d4ed8;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            display: inline-block;
            text-decoration: none;
            width: 100%;
        }
        button:hover, .btn:hover {
            background: #1e40af;
        }
        input {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        .error {
            color: #dc2626;
            font-size: 13px;
            margin-top: -10px;
            margin-bottom: 10px;
        }
        .text-sm {
            font-size: 14px;
        }
        .text-gray {
            color: #666;
        }
        a {
            color: #1d4ed8;
        }
        code {
            background: #f3f4f6;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
            font-size: 13px;
        }
        pre {
            background: #1e293b;
            color: #e2e8f0;
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
            font-size: 13px;
            margin-top: 10px;
        }
        ul {
            margin-left: 20px;
        }
    </style>
    @livewireStyles
</head>
<body>
    <div class="container">
        {{ $slot }}
    </div>

    @livewireScripts
</body>
</html>


resources/views/errors/404.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Not Found - PostHog Laravel Example</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            line-height: 1.6;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 40px;
            margin-top: 50px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        h1 {
            font-size: 72px;
            color: #1d4ed8;
            margin-bottom: 15px;
        }
        h2 {
            font-size: 24px;
            color: #333;
            margin-bottom: 15px;
        }
        p {
            color: #666;
            margin-bottom: 25px;
        }
        .btn {
            background: #1d4ed8;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
        }
        .btn:hover {
            background: #1e40af;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>404</h1>
            <h2>Page Not Found</h2>
            <p>The page you're looking for doesn't exist.</p>
            <a href="/" class="btn">Go Home</a>
        </div>
    </div>
</body>
</html>


resources/views/errors/500.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Server Error - PostHog Laravel Example</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            line-height: 1.6;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 40px;
            margin-top: 50px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        h1 {
            font-size: 72px;
            color: #dc2626;
            margin-bottom: 15px;
        }
        h2 {
            font-size: 24px;
            color: #333;
            margin-bottom: 15px;
        }
        p {
            color: #666;
            margin-bottom: 25px;
        }
        .btn {
            background: #1d4ed8;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
        }
        .btn:hover {
            background: #1e40af;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>500</h1>
            <h2>Internal Server Error</h2>
            <p>Something went wrong on our end.</p>
            <a href="/" class="btn">Go Home</a>
        </div>
    </div>
</body>
</html>


resources/views/livewire/auth/login.blade.php

<div>
    <div class="card">
        <h1>Welcome to PostHog Laravel Example</h1>
        <p class="text-gray mb-4">This example demonstrates how to integrate PostHog with a Laravel application.</p>

        <form wire:submit="login">
            <label for="email">Email</label>
            <input
                type="email"
                id="email"
                wire:model="email"
                required
            >
            @error('email') <div class="error">{{ $message }}</div> @enderror

            <label for="password">Password</label>
            <input
                type="password"
                id="password"
                wire:model="password"
                required
            >
            @error('password') <div class="error">{{ $message }}</div> @enderror

            <div style="margin-bottom: 15px;">
                <label style="display: inline; font-weight: normal;">
                    <input type="checkbox" wire:model="remember" style="width: auto; margin-right: 5px;">
                    Remember me
                </label>
            </div>

            <button type="submit">Login</button>
        </form>

        <p style="margin-top: 16px;" class="text-sm text-gray">
            Don't have an account? <a href="{{ route('register') }}">Sign up here</a>
        </p>
        <p class="text-sm text-gray">
            <strong>Tip:</strong> Default credentials are [email protected]/admin
        </p>
    </div>

    <div class="card">
        <h2>Features Demonstrated</h2>
        <ul class="text-gray">
            <li>User registration and identification</li>
            <li>Event tracking</li>
            <li>Feature flags</li>
            <li>Error tracking</li>
        </ul>
    </div>
</div>


resources/views/livewire/auth/register.blade.php

<div>
    <div class="card">
        <h1>Create an Account</h1>
        <p class="text-gray mb-4">Sign up to explore the PostHog Laravel integration example.</p>

        <form wire:submit="register">
            <label for="email">Email *</label>
            <input
                type="email"
                id="email"
                wire:model="email"
                required
            >
            @error('email') <div class="error">{{ $message }}</div> @enderror

            <label for="password">Password *</label>
            <input
                type="password"
                id="password"
                wire:model="password"
                required
            >
            @error('password') <div class="error">{{ $message }}</div> @enderror

            <label for="password_confirmation">Confirm Password *</label>
            <input
                type="password"
                id="password_confirmation"
                wire:model="password_confirmation"
                required
            >

            <button type="submit">Sign Up</button>
        </form>

        <p style="margin-top: 16px;" class="text-sm text-gray">
            Already have an account? <a href="{{ route('login') }}">Login here</a>
        </p>
    </div>

    <div class="card">
        <h2>PostHog Integration</h2>
        <p class="text-gray">When you sign up, the following PostHog events are captur