PHP code example of rawand201 / filament-spatie-lighthouse

1. Go to this page and download the library: Download rawand201/filament-spatie-lighthouse library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rawand201 / filament-spatie-lighthouse example snippets


use FilamentSpatieLighthouse\FilamentSpatieLighthousePlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...
        ->plugin(FilamentSpatieLighthousePlugin::make());
}

FilamentSpatieLighthousePlugin::make()
    ->navigationGroup('Tools')        // set or override the navigation group
    ->navigationLabel('Lighthouse')   // set the nav item label
    ->navigationIcon('heroicon-o-bolt') // set the nav item icon
    ->navigationSort(5)               // set the sort order
    ->authorize(fn (): bool => auth()->user()->can('view lighthouse'));

// Where to store audit metadata (scores, timestamps, etc.)
// Options: 'database' (default) | 'cache'
'result_store' => env('LIGHTHOUSE_RESULT_STORE', 'database'),

// Options: 'database' (default) | 'filesystem'
'raw_results_driver' => env('LIGHTHOUSE_RAW_RESULTS_DRIVER', 'database'),

// Laravel disk to use when driver is 'filesystem'
'raw_results_disk'   => env('LIGHTHOUSE_RAW_RESULTS_DISK', 'local'),

// Directory within the disk
'raw_results_path'   => env('LIGHTHOUSE_RAW_RESULTS_PATH', 'lighthouse-results'),

'database' => [
    // Use a specific DB connection (null = app default)
    'connection' => env('LIGHTHOUSE_DB_CONNECTION', null),
],

// TTL in seconds when using the 'cache' result store
'cache_ttl' => env('LIGHTHOUSE_CACHE_TTL', 86400), // 24 hours

// Lighthouse audit timeout in seconds
// When running synchronously, PHP's max_execution_time must be higher than this value
'default_timeout' => env('LIGHTHOUSE_TIMEOUT', 180),

// Auto-prune records older than N days (database store only, uses MassPrunable)
// Run: php artisan model:prune --model=FilamentSpatieLighthouse\\Models\\LighthouseAuditResult
'keep_history_for_days' => env('LIGHTHOUSE_KEEP_HISTORY_DAYS', 30),

'default_categories' => [
    'performance',
    'accessibility',
    'best-practices',
    'seo',
],

'use_queue'          => env('LIGHTHOUSE_USE_QUEUE', false),
'queue_connection'   => env('LIGHTHOUSE_QUEUE_CONNECTION', null),
'queue_name'         => env('LIGHTHOUSE_QUEUE_NAME', 'default'),
'queue_tries'        => env('LIGHTHOUSE_QUEUE_TRIES', 1),
'queue_timeout'      => env('LIGHTHOUSE_QUEUE_TIMEOUT', 300),

'score_thresholds' => [
    'good'             => 90, // >= 90 → green
    'needs_improvement' => 50, // >= 50 → orange, < 50 → red
],

'metric_thresholds' => [
    'first_contentful_paint'  => ['good' => 1800,  'needs_improvement' => 3000,  'unit' => 'ms'],
    'largest_contentful_paint'=> ['good' => 2500,  'needs_improvement' => 4000,  'unit' => 'ms'],
    'speed_index'             => ['good' => 3400,  'needs_improvement' => 5800,  'unit' => 'ms'],
    'total_blocking_time'     => ['good' => 200,   'needs_improvement' => 600,   'unit' => 'ms'],
    'time_to_interactive'     => ['good' => 3800,  'needs_improvement' => 7300,  'unit' => 'ms'],
    'cumulative_layout_shift' => ['good' => 0.1,   'needs_improvement' => 0.25,  'unit' => 'score'],
],

'display' => [
    'show_category_scores'       => true,
    'show_audit_info'            => true,
    'show_html_report'           => true,
    'show_performance_metrics'   => true,
    'show_failed_audits'         => true,
    'show_history'               => true,

    // Number of failed audits shown before a "Show All" toggle
    'failed_audits_initial_count' => 10,

    // Max height of the failed audits scrollable container (CSS value)
    'failed_audits_max_height'   => '800px',

    // How many history records to show per URL
    'history_count'              => 5,

    // Table auto-refresh interval (null to disable)
    'table_poll_interval'        => '30s',

    // Toggle individual table row actions
    'table_actions' => [
        'view'          => true,
        'view_html'     => true,
        'download_html' => true,
        'delete'        => true,
    ],
],

'export' => [
    'enabled' => env('LIGHTHOUSE_EXPORT_ENABLED', true),
    'formats' => ['csv', 'json'],
    'disk'    => env('LIGHTHOUSE_EXPORT_DISK', 'local'),
    'path'    => env('LIGHTHOUSE_EXPORT_PATH', 'lighthouse-exports'),
],

'scheduling' => [
    'enabled'           => env('LIGHTHOUSE_SCHEDULING_ENABLED', true),
    'default_frequency' => env('LIGHTHOUSE_SCHEDULE_FREQUENCY', 'daily'),

    // List of URLs to audit on a schedule
    'urls' => [
        // Simple entry — uses default_frequency and desktop form factor
        ['url' => 'https://example.com'],

        // Full entry
        [
            'url'         => 'https://example.com/blog',
            'frequency'   => 'weekly',   // 'hourly' | 'daily' | 'weekly'
            'form_factor' => 'mobile',   // 'desktop' | 'mobile'
        ],
    ],
],

'notifications' => [
    'email' => [
        'enabled'       => env('LIGHTHOUSE_NOTIFICATIONS_EMAIL_ENABLED', false),
        'to'            => env('LIGHTHOUSE_NOTIFICATIONS_EMAIL_TO', null),
        'on_failure'    => env('LIGHTHOUSE_NOTIFICATIONS_EMAIL_ON_FAILURE', true),
        'on_completion' => env('LIGHTHOUSE_NOTIFICATIONS_EMAIL_ON_COMPLETION', false),
    ],
    'slack' => [
        'enabled'       => env('LIGHTHOUSE_NOTIFICATIONS_SLACK_ENABLED', false),
        'webhook_url'   => env('LIGHTHOUSE_NOTIFICATIONS_SLACK_WEBHOOK_URL', null),
        'channel'       => env('LIGHTHOUSE_NOTIFICATIONS_SLACK_CHANNEL', null),
        'on_failure'    => env('LIGHTHOUSE_NOTIFICATIONS_SLACK_ON_FAILURE', true),
        'on_completion' => env('LIGHTHOUSE_NOTIFICATIONS_SLACK_ON_COMPLETION', false),
    ],
],

'endpoints' => [
    'enabled'      => env('LIGHTHOUSE_ENDPOINTS_ENABLED', false),
    'secret_token' => env('LIGHTHOUSE_ENDPOINTS_SECRET_TOKEN', null),
    'prefix'       => env('LIGHTHOUSE_ENDPOINTS_PREFIX', 'lighthouse-api'),
],

'raw_results_driver' => 'filesystem',
'raw_results_disk'   => 's3',
'raw_results_path'   => 'lighthouse/raw',

use FilamentSpatieLighthouse\Jobs\RunLighthouseAuditJob;

RunLighthouseAuditJob::dispatch(
    url: 'https://example.com',
    categories: ['performance', 'seo'],
    formFactor: 'mobile',
    userAgent: 'MyBot/1.0',
    headers: ['Authorization' => 'Bearer secret'],
    throttleCpu: true,
    throttleNetwork: true,
    timeoutSeconds: 180,
    userId: (string) auth()->id(),
);

'scheduling' => [
    'enabled'           => true,
    'default_frequency' => 'daily',
    'urls' => [
        ['url' => 'https://example.com'],
        ['url' => 'https://example.com/shop', 'frequency' => 'hourly'],
        ['url' => 'https://example.com/blog', 'frequency' => 'weekly', 'form_factor' => 'mobile'],
    ],
],

use FilamentSpatieLighthouse\Events\AuditEndedEvent;
use FilamentSpatieLighthouse\Events\AuditFailedEvent;
use FilamentSpatieLighthouse\Events\AuditStartingEvent;

// In EventServiceProvider or using #[AsEventListener]:

Event::listen(AuditEndedEvent::class, function (AuditEndedEvent $event) {
    // $event->url          — the audited URL
    // $event->scores       — ['performance' => 87, 'accessibility' => 100, ...]
    // $event->userId       — nullable string, set when audit was triggered by a user
});

Event::listen(AuditFailedEvent::class, function (AuditFailedEvent $event) {
    // $event->url
    // $event->exception
    // $event->userId
});

Event::listen(AuditStartingEvent::class, function (AuditStartingEvent $event) {
    // $event->url
    // $event->categories   — array of category strings
    // $event->formFactor   — 'desktop' | 'mobile'
    // $event->userId
});

use FilamentSpatieLighthouse\ResultStores\ResultStore;
use FilamentSpatieLighthouse\ResultStores\StoredAuditResults\StoredAuditResults;
use Spatie\Lighthouse\LighthouseResult;

class RedisResultStore implements ResultStore
{
    public function save(string $url, LighthouseResult $result): void
    {
        // persist $result->rawResults(), $result->scores(), etc.
    }

    public function latestResults(?string $url = null): ?StoredAuditResults
    {
        // return a StoredAuditResults instance or null
        return new StoredAuditResults(
            url: $url,
            finishedAt: $finishedAt,
            rawResults: $rawResults,
            scores: $scores,
        );
    }

    public function getHistory(?string $url = null, int $limit = 10): array
    {
        // return an array of result arrays
        return [];
    }
}

use FilamentSpatieLighthouse\ResultStores\ResultStore;

$this->app->singleton(ResultStore::class, RedisResultStore::class);

new StoredAuditResults(
    url: string,
    finishedAt: ?Carbon,
    rawResults: array,          // full Lighthouse JSON, keyed by audit id
    scores: array,              // ['performance' => 87, 'accessibility' => 100, ...]
    rawResultPath: ?string,     // filesystem path, or null if stored inline
);

namespace App\Filament\Pages;

use FilamentSpatieLighthouse\Pages\LighthouseResults as BaseLighthouseResults;

class LighthouseResults extends BaseLighthouseResults
{
    // Override table columns, actions, header widgets, etc.
}

FilamentSpatieLighthousePlugin::make()
    ->usingPage(\App\Filament\Pages\LighthouseResults::class)
bash
php artisan vendor:publish --tag="filament-spatie-lighthouse-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="filament-spatie-lighthouse-config"
bash
php artisan queue:work --queue=lighthouse --timeout=300
bash
php artisan lighthouse:schedule https://example.com --form-factor=mobile
bash
php artisan lighthouse:audit https://example.com
php artisan lighthouse:audit https://example.com --timeout=240
bash
php artisan lighthouse:schedule https://example.com
php artisan lighthouse:schedule https://example.com --form-factor=mobile --timeout=180
php artisan lighthouse:schedule https://example.com --categories=performance --categories=seo
bash
php artisan model:prune --model="FilamentSpatieLighthouse\Models\LighthouseAuditResult"