Laravel lifecycle
Laravel Application Lifecycle
Laravel follows a structured lifecycle when handling HTTP requests. Understanding this flow helps in debugging, performance optimization, and writing better middleware. Here's the complete breakdown:
1. Entry Point: public/index.php
All requests start here. This file:
Loads Composer's autoloader
Bootstraps the Laravel application
Creates an instance of the application kernel (either HTTP or Console)
require __DIR__.'/../vendor/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php';
2. Application Initialization
The
bootstrap/app.php
file creates the application instanceRegisters base service providers
Binds important interfaces (Kernel, ExceptionHandler)
$app = new Illuminate\Foundation\Application( dirname(__DIR__) );
3. Kernel Handling
For HTTP requests:
App\Http\Kernel
For console commands:
App\Console\Kernel
The kernel:
Loads environment variables
Loads configuration
Handles exceptions
Runs bootstrap providers (error handling, logging, etc.)
4. Service Providers Registration
All providers listed in
config/app.php
are registeredThe
register()
method of each provider is calledProviders can register bindings in the service container
5. Service Providers Boot
After registration, the
boot()
method is called for all providersThis is where providers can perform initialization
6. Request Handling
The request is converted to a Symfony
Request
instancePasses through middleware stack (global, route middleware)
Middleware can modify requests/responses or short-circuit the process
7. Router Dispatch
The router matches the request to a route
Route parameters are resolved
Controller/method is determined
8. Controller Execution
If route uses a controller:
Controller is instantiated (via service container)
Method dependencies are injected
Method is executed
If closure route, the closure is executed
9. Response Preparation
Controller/closure returns a response
Response passes back through middleware
Final response is sent to client
10. Termination
Any terminable middleware runs after response is sent
Application performs cleanup
Key Components in the Lifecycle
Service Container: The heart of Laravel, manages class dependencies
Service Providers: Extend application functionality
Middleware: Filter HTTP requests entering your application
Request/Response: Symfony components handling HTTP messages
Router: Matches URLs to controller actions or closures
Visual Flow
Client Request ↓ public/index.php ↓ Bootstrap (app.php) ↓ HTTP Kernel / Console Kernel ↓ Service Providers (register → boot) ↓ Request → Middleware Pipeline ↓ Router → Controller/Closure ↓ Response ← Middleware ↓ Client Response ↓ Terminable Middleware