When a production request returns the wrong tenant's data, a policy sees a model you did not expect, or a value disappears between middleware and a controller, the tempting response is to add another log line. That can find the symptom, but it does not tell you which part of Laravel owns the value or how long it is allowed to live.
Laravel's request lifecycle is that map. It explains how the front controller creates an application, how the HTTP kernel constructs a middleware pipeline, when routing and model binding happen, and why a response travels back through the same stack. It also draws a boundary that matters in long-running Octane workers: application booting is not the same thing as handling one request.
This is not an invitation to replace framework internals. Most applications should use ordinary routes, middleware, controllers, form requests, and service providers. Understanding their order makes those extension points predictable.
Start at the front controller, not the route file
For a normal web request, the web server sends every non-static request to
public/index.php. In current Laravel applications that file is deliberately
small: it loads Composer's autoloader, obtains the already-configured
application, captures the Symfony-backed HTTP request, and asks Laravel to
handle it.
<?php
declare(strict_types=1);
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
require __DIR__.'/../vendor/autoload.php';
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());
Request::capture() reads PHP's superglobals once and turns them into an
Illuminate\Http\Request. That is why a controller should receive the request
from Laravel instead of building its own from $_POST: it would bypass the
framework's normalization, trusted-proxy handling, input helpers, and test
fixtures.
The application instance comes from bootstrap/app.php. In Laravel 12 and 13,
this is where an application declares routes, middleware aliases, exception
configuration, and other bootstrap hooks. The framework still has an HTTP
kernel internally; applications no longer need an app/Http/Kernel.php class
just to list middleware.
<?php
declare(strict_types=1);
use App\Http\Middleware\RequireOrganization;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
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): void {
$middleware->alias([
'organization' => RequireOrganization::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (\DomainException $exception, Request $request): ?JsonResponse {
if (! $request->expectsJson()) {
return null;
}
return response()->json([
'message' => $exception->getMessage(),
], 422);
});
})
->create();
The closure configures the application. It does not run again every time a route is matched, nor is it a good place for request-specific database work. Providers and bootstrap hooks establish capabilities; middleware and the route action use them for an individual request.
Booting the application and serving a request are different phases
On a traditional PHP-FPM deployment, a fresh PHP process handles a request and then ends. That makes booting and serving look inseparable. They are not.
Laravel loads configuration, registers service providers, creates bindings, and
boots providers before it dispatches the captured request through the global
middleware and the router. A provider's register() method describes container bindings. Its
boot() method runs after providers have registered, so it can use bindings,
events, routes, and macros. Neither is the right place to read the current
account from the request.
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Billing\InvoiceNumberGenerator;
use App\Billing\SequentialInvoiceNumberGenerator;
use Illuminate\Support\ServiceProvider;
final class BillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(
InvoiceNumberGenerator::class,
SequentialInvoiceNumberGenerator::class,
);
}
}
Avoid resolving the current request in a singleton during register(). It may
work in PHP-FPM by accident and become a cross-request state leak under Octane.
Middleware is nested, not a flat checklist
The kernel creates a pipeline. Global middleware wraps every request; after the router selects a route, Laravel adds that route's middleware group and aliases. Each middleware decides whether to call the next layer. The outgoing response then unwinds through the layers in reverse order.
That shape is easier to see in a trace middleware than in a diagram. It adds a
correlation ID before calling the next layer, writes it to the response after
the controller returns, and records a final metric in terminate() after the
response has been sent.
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
final class TraceRequest
{
public function handle(Request $request, Closure $next): Response
{
$traceId = $request->headers->get('X-Request-Id', (string) Str::uuid());
$request->attributes->set('trace_id', $traceId);
$response = $next($request);
$response->headers->set('X-Request-Id', $traceId);
return $response;
}
public function terminate(Request $request, Response $response): void
{
logger()->info('HTTP request completed', [
'trace_id' => $request->attributes->get('trace_id'),
'status' => $response->getStatusCode(),
]);
}
}
The handle() method is before-and-after code around the rest of the pipeline.
If it returns a redirect, a response, or throws before $next($request), the
controller will never run. That is appropriate for authentication, maintenance
mode, rate limiting, and an invalid tenant header. It is a poor place for a
rule that only one endpoint needs: use a form request, policy, or action for
that narrower concern.
Register a global concern deliberately, and use an alias only on the routes that need it:
<?php
declare(strict_types=1);
use App\Http\Controllers\InvoiceController;
use Illuminate\Support\Facades\Route;
Route::middleware(['auth', 'organization'])
->get('/invoices/{invoice}', InvoiceController::class)
->name('invoices.show');
Keep the global append(TraceRequest::class) call in bootstrap/app.php, not
in a route file. Route middleware runs only after Laravel has identified the
route; global middleware runs early enough that no route parameters exist yet.
Routing, bindings, authorization, and the action
Once routing middleware enters the router, Laravel matches method and URI,
substitutes route parameters, runs route model binding, and invokes the action.
Binding is performed by the SubstituteBindings middleware that the web and
api groups include, so middleware ordered before it sees raw parameter values.
Implicit binding turns {invoice} into an Invoice using its route key. A
custom key such as a public UUID keeps database IDs out of the URL, but it does
not authorize access. The controller must still check the authenticated actor.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Invoice;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class InvoiceController
{
use AuthorizesRequests;
public function __invoke(Request $request, Invoice $invoice): JsonResponse
{
$this->authorize('view', $invoice);
return response()->json([
'id' => $invoice->public_id,
'number' => $invoice->number,
'total_cents' => $invoice->total_cents,
'currency' => $invoice->currency,
]);
}
}
An authorization middleware can reject an unauthenticated user before this point. A policy makes the resource-specific decision after binding. Treating them as alternatives creates either duplicated checks or an authorization gap. The useful sequence is: establish identity, resolve the resource, then decide whether that identity may perform this action on this resource.
If a request fails at any layer, Laravel's exception configuration receives the exception and converts it into a response. Do not catch every exception inside a controller merely to return a generic 500. Let unexpected exceptions keep their stack trace and reporting path; map expected domain failures at a central boundary where HTTP representation belongs.
The return trip is still part of the request
The controller's JsonResponse, redirect, view, streamed response, or Inertia
response does not go directly to Nginx. It travels out through every middleware
that called $next. That is when response headers, cookies, CORS handling, and
transaction-style cleanup often happen.
Terminable middleware receives both request and response after the response
has been prepared. Depending on the SAPI and server, Laravel can finish the
client response before running termination work, but it is not a durable job
queue. A slow API call, retried invoice export, or essential webhook belongs in
a queued job with retries and monitoring, not in terminate().
<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
final class RecordRequestMetric implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
public function __construct(
public readonly string $traceId,
public readonly int $status,
) {
}
public function handle(): void
{
logger()->info('Persisted HTTP metric', [
'trace_id' => $this->traceId,
'status' => $this->status,
]);
}
}
For essential work, dispatch this job from an action that owns the business event, preferably after a committed transaction where appropriate. Logging a request is not the same as proving a payment was recorded.
Caches change startup, not application semantics
Production deployment often runs Laravel's optimization commands. Configuration
caching compiles values returned by config/*.php into one file. After that,
calling env() from a controller or service is unreliable because Laravel no
longer needs to load the environment file at runtime. Put environment reads in
configuration and inject or read config() in application code.
<?php
declare(strict_types=1);
namespace App\Notifications;
final readonly class SenderAddress
{
public function __construct(
public string $address,
) {
}
public static function fromConfiguration(): self
{
return new self(
address: (string) config('mail.from.address'),
);
}
}
php artisan optimize
php artisan config:clear
php artisan route:list
optimize is a deployment convenience for supported caches such as config,
routes, events, and compiled views. It is not a general performance button,
and route caching is safest with controller routes: closure routes are
serialized with extra restrictions. If deployment changes an
environment value, build the config cache in the environment that will run it
and clear/rebuild it as part of that deployment—not by editing .env while
workers continue with old in-memory config.
Octane makes lifetime decisions visible
Octane keeps a worker alive for many requests. Providers boot once per worker,
and a singleton remains in that worker until it is recycled. A singleton that
captures mutable request state can therefore give the next customer the
previous customer's tenant ID.
This is unsafe:
<?php
declare(strict_types=1);
namespace App\Tenancy;
use Illuminate\Http\Request;
final readonly class CurrentTenant
{
public function __construct(
public string $tenantId,
) {
}
public static function fromRequest(Request $request): self
{
return new self((string) $request->header('X-Tenant-Id'));
}
}
// Do not do this in a provider:
// $this->app->singleton(CurrentTenant::class, fn (): CurrentTenant => CurrentTenant::fromRequest(request()));
Bind request context as scoped and populate it through middleware instead.
Laravel flushes scoped instances at the end of a request or queue job, giving
the next lifecycle a new context.
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Tenancy\CurrentTenant;
use Illuminate\Support\ServiceProvider;
final class TenancyServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->scoped(CurrentTenant::class, function (): CurrentTenant {
throw new \LogicException('CurrentTenant must be set by tenancy middleware.');
});
}
}
The middleware can then resolve a dedicated mutable context or pass tenant data to the action explicitly. The best choice depends on how deeply tenant context crosses boundaries; explicit parameters are easier to test, while a scoped context can reduce repetitive plumbing in a carefully designed tenancy layer.
Do not use Octane::tick() as a repair for leaked request state. It is for
deliberate periodic worker maintenance. Correct bindings, explicit cleanup of
external client state, and worker recycling are the primary safety mechanisms.
When not to use lifecycle hooks
Do not introduce global middleware because a controller needs one derived value. Pass the value to an action, use a form request for input validation, or use a policy for authorization. Do not put transactional business work in a terminable middleware; queue it after commit. Do not use a service provider to query the database for the active user, locale, or tenant. And do not create a custom kernel or manually call the container to "control" resolution when a route, binding, provider, or middleware already expresses the intent.
The alternative is not fewer abstractions at all costs. It is the narrowest Laravel extension point that owns the concern: provider for application setup, middleware for request-wide transport rules, form request for input, policy for access, action for use-case behaviour, and job for durable asynchronous work.
Failure modes to test before production
The lifecycle produces failures that unit tests of a controller alone will miss:
- A global middleware assumes route parameters exist and fails before routing.
- A route binding returns a model from another tenant, while the policy is absent or incorrectly written.
- A
terminate()task is treated as reliable work and disappears on worker restart. - A deployment changes
.envwithout rebuilding cached configuration. - An Octane singleton stores request or authenticated-user state and leaks it to the next request.
Write feature tests that exercise the route through its middleware and policy, then run a realistic deployment with caches enabled. For Octane, add a test or operational check that sends two requests with different tenant identities to the same worker. The controller is only one station on the route from a socket to a response; production correctness depends on the whole path.