PHP code example of backstage / laravel-static

1. Go to this page and download the library: Download backstage/laravel-static 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/ */

    

backstage / laravel-static example snippets


use Backstage\LaravelStatic\Middleware\StaticResponse;

Route::get('/', function () {
    return view('welcome');
})->middleware(StaticResponse::class);

// Or apply to route groups
Route::middleware([StaticResponse::class])->group(function () {
    Route::get('/about', [PageController::class, 'about']);
    Route::get('/contact', [PageController::class, 'contact']);
    Route::get('/blog', [BlogController::class, 'index']);
});

'driver' => 'crawler', // Options: 'crawler' or 'routes'

'enabled' => env('STATIC_ENABLED', true),

'build' => [
    'clear_before_start' => true,    // Clear existing cache before rebuilding
    'concurrency' => 5,               // Number of concurrent HTTP requests
    'accept_no_follow' => true,       // Follow nofollow links when crawling
    'default_scheme' => 'https',      // URL scheme for crawler requests
    'force_root_url' => env('STATIC_FORCE_ROOT_URL', false), // Force generated links to app.url during builds
    'crawl_observer' => \Backstage\LaravelStatic\Crawler\StaticCrawlObserver::class,
    'crawl_profile' => \Spatie\Crawler\CrawlProfiles\CrawlInternalUrls::class,
    'bypass_header' => [
        'name' => 'X-Laravel-Static',
        'value' => 'off',
    ],
],

'whitelist' => [
    'hosts' => null,  // null = cache every host; array = only these hosts
],

'whitelist' => [
    'hosts' => [
        $host = parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST),
        'www.' . $host,
    ],
],

'files' => [
    'disk' => env('STATIC_DISK', 'public'),  // Laravel filesystem disk
    ''filepath_max_length' => 4096,            // Maximum file path length
    'filename_max_length' => 255,             // Maximum filename length
],

'options' => [
    'on_termination' => false,  // Save cache after response sent (async)
    'minify_html' => false,     // Minify HTML before caching
],

'compression' => [
    'gzip' => true,             // Write a .gz copy (env: STATIC_COMPRESS_GZIP)
    'gzip_level' => 9,          // 0-9, higher is smaller/slower
    'brotli' => false,          // Write a .br copy (env: STATIC_COMPRESS_BROTLI)
    'brotli_level' => 11,       // 0-11
    'keep_uncompressed' => true, // Also keep the plain .html copy
],

// config/static.php
'options' => [
    'minify_html' => true,
],

use Backstage\LaravelStatic\Facades\StaticCache;

// Clear all cache
StaticCache::clear();

// Clear specific paths
StaticCache::clear(['/about', '/contact']);

use Backstage\Static\Laravel\Facades\StaticCache;

// Rebuild a single page
StaticCache::build('https://example.com/blog/my-post');

// Rebuild several at once
StaticCache::build([
    'https://example.com/blog/my-post',
    'https://example.com/blog',
]);

use Backstage\Static\Laravel\Jobs\BuildStaticPage;

BuildStaticPage::dispatch($post->url());

namespace App\Crawlers;

use Backstage\LaravelStatic\Crawler\StaticCrawlObserver;
use Psr\Http\Message\UriInterface;
use Psr\Http\Message\ResponseInterface;

class CustomCrawlObserver extends StaticCrawlObserver
{
    public function crawled(UriInterface $url, ResponseInterface $response, ?UriInterface $foundOnUrl = null): void
    {
        // Add custom logic before caching
        logger()->info("Caching: {$url}");

        parent::crawled($url, $response, $foundOnUrl);
    }
}

'build' => [
    'crawl_observer' => \App\Crawlers\CustomCrawlObserver::class,
],

namespace App\Crawlers;

use Psr\Http\Message\UriInterface;
use Spatie\Crawler\CrawlProfiles\CrawlProfile;

class CustomCrawlProfile extends CrawlProfile
{
    public function shouldCrawl(UriInterface $url): bool
    {
        $path = $url->getPath();

        // Skip admin routes
        if (str_starts_with($path, '/admin')) {
            return false;
        }

        // Skip API routes
        if (str_starts_with($path, '/api')) {
            return false;
        }

        return true;
    }
}

// These routes will be cached
Route::middleware([StaticResponse::class])->group(function () {
    Route::get('/', [HomeController::class, 'index']);
    Route::get('/about', [PageController::class, 'about']);
});

// These routes will NOT be cached (no middleware)
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/user/{id}', [UserController::class, 'show']); // Has parameters

  // config/static.php
  'build' => [
      'force_root_url' => true,
  ],
  

'options' => [
    'on_termination' => true,
],

use Backstage\LaravelStatic\Facades\StaticCache;

class Post extends Model
{
    protected static function booted()
    {
        static::saved(function (Post $post) {
            StaticCache::clear([
                "/blog/{$post->slug}",
                '/blog',
            ]);
        });

        static::deleted(function (Post $post) {
            StaticCache::clear([
                "/blog/{$post->slug}",
                '/blog',
            ]);
        });
    }
}

use Backstage\Static\Laravel\Jobs\BuildStaticPage;

static::updated(function (Post $post) {
    BuildStaticPage::dispatch($post->url());
});

// app/Console/Kernel.php or bootstrap/app.php (Laravel 11+)
Schedule::command('static:build')->daily();
bash
php artisan vendor:publish --tag="laravel-static-config"
bash
php artisan vendor:publish --tag="laravel-static-migrations"
php artisan migrate
bash
php artisan static:build
bash
php artisan static:build
bash
php artisan static:clear
bash
php artisan static:clear --force
bash
php artisan static:clear --uri=/about --uri=/contact
bash
php artisan static:clear --routes=home --routes=about --routes=blog.index
bash
php artisan static:clear --domain=example.com
php artisan static:clear --domain=subdomain.example.com
bash
#!/bin/bash
# deploy.sh

php artisan static:clear
php artisan static:build
bash
composer analyse