All posts
laravelpreview-environmentstutorialworkflow

Laravel Branch Previews: The Four Things That Break on a Second Hostname

PreviewDrop Team·November 30, 2026·8 min read

You push a branch. The build passes. You open the preview URL and the login form returns 419 Page Expired. You reload, the page renders without CSS. You fix that, log in, and every redirect sends you to http://localhost:8000.

None of these are preview-tool bugs. They are four Laravel defaults that assume one hostname, one scheme, and a php artisan serve process that quietly does work you never configured. A preview environment breaks all four assumptions at once.

This guide covers each one, the exact symptom you'll see, and the fix. Every snippet drops into a real Laravel app.

What a preview environment actually is

A preview environment is a running copy of your app, built from one branch, reachable at its own HTTPS URL, and destroyed when its lifetime expires. For Laravel that means a real container running php-fpm behind a web server — not artisan serve — a real database, and a hostname that didn't exist yesterday.

If your team reviews Laravel changes by pulling the branch and running php artisan serve on a laptop, you already know the cost. The reviewer needs your .env, your database, and your seed data. Half the time they get a different result because their local database has different rows.

The fix is a URL per branch. Getting there is mostly about teaching Laravel that it can live at more than one address.

Setting 1: APP_URL, proxies, and the localhost redirect

This is the one that wastes the most time, because the app works — it just sends people to the wrong place.

Laravel builds absolute URLs from APP_URL. Behind a reverse proxy that terminates TLS, Laravel also needs to know the original request was HTTPS. Without that, url() and redirect() generate http:// links, and the browser either downgrades or blocks the request.

// config/app.php — read from env, never hardcode
'url' => env('APP_URL', 'http://localhost'),

// app/Http/Middleware/TrustProxies.php
protected $proxies = '*';

TrustProxies with '*' tells Laravel to trust the X-Forwarded-Proto and X-Forwarded-Host headers the router sets. Without it, $request->isSecure() returns false and secure_url() produces the wrong scheme.

Set APP_URL in the preview environment's variables to the preview's own origin. Preview hostnames follow prv-<id>.previews.previewdrop.dev, so if your preview URL is stable per project you can set it once; if it changes per deploy, set it at deploy time from the platform's environment.

Setting 2: the 419 Page Expired — session domain and CSRF

The 419 is Laravel's CSRF token mismatch. On a preview it has two causes, and they look identical.

The first is the session cookie. If SESSION_DOMAIN is pinned to your production domain, the browser never sends the cookie to the preview host, so the token in the form has no matching session.

// config/session.php
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', true),
'same_site' => 'lax',

Leave SESSION_DOMAIN unset (null) for previews. A null domain scopes the cookie to the exact host, which is what you want when every preview is a different hostname.

The second cause is Laravel Sanctum. If you use Sanctum for SPA authentication, its stateful domain list is checked against the request's origin:

// config/sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
    env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),

Adding the preview host to SANCTUM_STATEFUL_DOMAINS fixes it. Note that Sanctum matches on host, not on a wildcard — you cannot write *.previews.previewdrop.dev and expect it to work. If your preview hostnames are unique per deploy, append the current host at boot from APP_URL.

Setting 3: assets and the Vite manifest

The preview loads, the HTML is there, and the CSS is a 404. Or the page throws Vite manifest not found at: /app/public/build/manifest.json.

npm run dev serves assets from a dev server. A preview runs the built output, so the build has to happen and the manifest has to exist before the app boots:

#!/usr/bin/env bash
# the container's start command
set -euo pipefail

php artisan migrate --force
php artisan config:cache
php artisan route:cache
exec php-fpm -F

and the build step has to run npm ci && npm run build before that. If your project uses @vite in Blade templates, the manifest is mandatory — there is no fallback.

Two things to get right:

Use exec. Without it, php-fpm runs as a child of the shell, and the container's stop signal goes to the shell instead of the app. The preview then takes the full timeout to die instead of shutting down cleanly.

Run config:cache after the environment is set, not before. A cached config baked at image-build time freezes whatever APP_URL and SESSION_DOMAIN existed then. Cache at boot, in the start command, so the preview's own variables are the ones that get compiled in.

Setting 4: migrations and the PORT contract

A preview with an empty database is useless. A preview that shares the production database is dangerous.

Run migrations on startup against the preview's own database, and make the seed idempotent:

// database/seeders/PreviewSeeder.php
class PreviewSeeder extends Seeder
{
    public function run(): void
    {
        User::firstOrCreate(
            ['email' => 'reviewer@example.com'],
            ['name' => 'Preview Reviewer', 'password' => bcrypt(Str::random(32))]
        );
    }
}

firstOrCreate is safe to re-run; insert() with fixed IDs is not, and will fail on the second boot with a duplicate-key error.

Then there's PORT. PreviewDrop sets PORT, HOST, and HOSTNAME in the container — nothing else. There is no injected PREVIEW_URL, so don't write code that expects one. If your app needs to know its own URL, read it from the request (url()->current()) or from APP_URL.

Your web server has to listen on $PORT and bind to 0.0.0.0, not 127.0.0.1. A container listening only on loopback is unreachable from the router, and the health check fails with a connection refused that looks like a crash.

Never point a preview at your staging database and call it done. Staging data drifts, contains real customer rows, and a preview that writes to it can corrupt the environment your team uses for pre-release testing.

The whole config, together

// config/app.php
'url' => env('APP_URL', 'http://localhost'),

// config/session.php
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', true),

// app/Http/Middleware/TrustProxies.php
protected $proxies = '*';

Plus SANCTUM_STATEFUL_DOMAINS including the preview host, npm run build in the build step, and php artisan migrate --force && php artisan config:cache in the start command.

That's the whole job. Four settings, one start script, and a build that produces the Vite manifest.

What you get when it works

Once these four are in place, a Laravel preview stops being a maintenance project. Push a branch, get a URL. The reviewer clicks it, sees the actual change running against a real database, and leaves a comment. No composer install, no .env file passed around, no "works on my machine."

The setup cost is one afternoon. The return is every future PR review — and every time a designer or PM needs to look at a change without asking an engineer to run it locally.

If you'd rather not maintain the container plumbing yourself, PreviewDrop detects a Laravel project from composer.json, builds the image, injects your environment variables, and gives every branch a live HTTPS URL that expires on its own. You keep the four settings above; the platform handles the rest.

Set up your first Laravel preview →

Or read the quickstart if you want to see the whole flow end to end before connecting a repo.

Want previews on your own pull requests? Start free — 2 concurrent previews, no credit card.