Request Lifecycle
Complete lifecycle of an HTTP request in Laravel
Request Lifecycle is the process an HTTP request goes through from entry to exit. Understanding this process is essential for Laravel developers to perform appropriate optimizations and debug issues.
Lifecycle Stages:
1. Entry Point: Request arrives at public/index.php. This file is Laravel's main entry point.
2. Bootstrap: Laravel application bootstraps. Service Container is initialized and environment configuration is loaded.
3. Service Providers: All registered Service Providers are registered and booted. Bindings are registered in container.
4. HTTP Kernel: Kernel receives request and applies middleware stack.
5. Middleware: Middlewares are executed in defined order. Each middleware can modify request or return response.
6. Routing: Routing system maps URL to appropriate Controller and Action. Route model binding is also performed at this stage.
7. Controller: Related Controller is instantiated and action method is executed. Dependency injection is also performed at this stage.
8. Response: Response is returned as View, JSON, Redirect or Response object.
9. Termination: Terminate middlewares are executed which are used for cleanup operations.
10. Response Send: Final response is sent to client.
Examples
Entry Point
<?php
// public/index.php
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
Main code that captures request and sends to Kernel.
Bootstrap Process
<?php
// Bootstrap process includes:
// 1. Load environment variables
// 2. Create application instance
// 3. Register service providers
// 4. Boot service providers
// In bootstrap/app.php
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
Bootstrap process that initializes application.
Middleware Pipeline
<?php
// Request flows through middleware:
// 1. Global Middleware
// 2. Route Middleware Groups (web/api)
// 3. Route Specific Middleware
// 4. Controller
// 5. Response
// 6. Terminate Middleware (reverse order)
// Example:
Request
-> TrustProxies
-> EncryptCookies
-> StartSession
-> VerifyCsrfToken
-> Authenticate
-> Controller
-> Response
-> Terminate Middleware
Middleware pipeline that request flows through.
Route Resolution
<?php
// Route resolution process:
// 1. Match URL pattern
// 2. Check route constraints
// 3. Resolve route model binding
// 4. Check middleware
// 5. Resolve controller/closure
// 6. Inject dependencies
Route::get('/users/{user}', [UserController::class, 'show']);
// Lifecycle:
// /users/1 -> Match route
// -> Resolve User model (id=1)
// -> Check auth middleware
// -> Instantiate UserController
// -> Inject User model
// -> Execute show() method
Route resolution process that finds route and executes controller.
Controller Execution
<?php
// Controller execution:
// 1. Instantiate controller
// 2. Resolve dependencies (DI)
// 3. Execute method
// 4. Generate response
class UserController extends Controller
{
public function show(User $user, UserService $service)
{
// User and UserService are injected automatically
$data = $service->getUserData($user);
return view('users.show', compact('user', 'data'));
}
}
// Lifecycle:
// 1. Resolve User model (route binding)
// 2. Resolve UserService (DI)
// 3. Execute show() method
// 4. Return view response
Controller execution that runs method and generates response.
Termination Phase
<?php
// Termination phase:
// 1. Response is sent to client
// 2. Terminate middleware execute (reverse order)
// 3. Cleanup operations
// 4. Logging
// 5. Memory cleanup
class LogRequestMiddleware
{
public function terminate($request, $response)
{
// This runs AFTER response is sent
Log::info('Request completed', [
'url' => $request->url(),
'status' => $response->status(),
'duration' => microtime(true) - LARAVEL_START
]);
}
}
Termination phase that executes after response is sent.
Exception Handling
<?php
// Exception can occur at any stage:
// 1. During bootstrap
// 2. During middleware execution
// 3. During route resolution
// 4. During controller execution
// Exception handler catches all exceptions
// In App\Exceptions\Handler:
public function render($request, Throwable $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json(['error' => 'Not found'], 404);
}
return parent::render($request, $exception);
}
// Exception handling lifecycle:
// Exception -> Handler -> Response -> Client
Exception handling that can handle exceptions at any stage of lifecycle.
Use Cases
- Deeper understanding of how Laravel works
- Debugging issues in request processing
- Performance optimization with lifecycle understanding
- Creating custom middleware to intercept requests
- Centralized exception handling
- Performance monitoring and profiling
Common Mistakes
- Assuming service providers boot on every request (deferred providers)
- Using services in register() that haven't been registered yet
- Forgetting that terminate middleware runs after response send
- Using singleton for stateful services
- Not understanding difference between HTTP and Console lifecycle
- Exception handling exposing sensitive information
Best Practices
- Use deferred providers for rarely used services
- In register() only do binding
- Use boot() to access other services
- Use terminate middleware for cleanup
- Implement exception handling properly
- Use route caching and config caching in production
- Optimize middleware
Edge Cases
- Exception in bootstrap process
- Exception in middleware execution
- Exception in route resolution
- Exception in controller execution
- Terminate middleware throwing exceptions
- Long-running requests that timeout
Performance Notes
- Bootstrap time can be reduced with deferred providers
- Route caching can reduce routing overhead by up to 50%
- Config caching can reduce config loading time
- Middleware optimization is important for performance
- Exception handling overhead should be minimized
- Laravel 11.x has performance improvements in lifecycle
Security Notes
- Ensure security middlewares are in appropriate places
- Exception handling should not expose sensitive information
- Bootstrap process should follow security best practices
- Route model binding should have validation
Interview Points
- What is the lifecycle of an HTTP request in Laravel?
- What is the difference between register() and boot() in service providers?
- How does middleware stack work?
- When does termination middleware execute?
- How does exception handling work in lifecycle?
- How can you optimize lifecycle?
Version Notes
- Laravel 11.x: Improved performance in request lifecycle
- Laravel 11.x: Improved bootstrap process
- Laravel 10.x: Improved middleware pipeline
- Laravel 9.x: Improved exception handling