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)

php

require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';

2. Application Initialization

  • The bootstrap/app.php file creates the application instance

  • Registers base service providers

  • Binds important interfaces (Kernel, ExceptionHandler)

php

$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 registered

  • The register() method of each provider is called

  • Providers can register bindings in the service container

5. Service Providers Boot

  • After registration, the boot() method is called for all providers

  • This is where providers can perform initialization

6. Request Handling

  • The request is converted to a Symfony Request instance

  • Passes 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

  1. Service Container: The heart of Laravel, manages class dependencies

  2. Service Providers: Extend application functionality

  3. Middleware: Filter HTTP requests entering your application

  4. Request/Response: Symfony components handling HTTP messages

  5. 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

To Top