How Laravel Works

A request travels through routing, middleware, a controller, and a view before a response is returned.

When a browser sends a request to a Laravel app, it flows through a predictable lifecycle:

  1. The request hits public/index.php, the single entry point.
  2. Routing decides which code should handle the URL.
  3. Middleware can inspect or reject the request (for example, checking authentication).
  4. A Controller runs your logic and talks to the database.
  5. A View (Blade template) renders HTML, which is returned as the response.

Understanding this flow helps you know where each piece of code belongs.

Example

Example · php
// Simplified request lifecycle (illustrative)
// Request  ->  Route  ->  Middleware  ->  Controller  ->  View  ->  Response

When to use it

  • A developer adds an authentication middleware to the route group so that unauthenticated requests are redirected before reaching any controller logic.
  • A team member traces a slow page response through the request lifecycle to discover that a middleware is triggering an extra database query on every request.
  • An architect designs a multi-tenant SaaS app by injecting a tenant-resolution middleware early in the pipeline so all downstream code runs in the correct tenant context.

More examples

Middleware stack in the HTTP Kernel

Illustrates the ordered middleware stack that every 'web' route passes through before hitting a controller.

Example · php
// app/Http/Kernel.php (excerpt)
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ],
];

Route dispatches to a controller

Demonstrates how Laravel automatically resolves a model from the URL segment via route-model binding before the controller method runs.

Example · php
// routes/web.php
Route::get('/posts/{post}', [PostController::class, 'show']);

// app/Http/Controllers/PostController.php
public function show(Post $post): View
{
    return view('posts.show', compact('post'));
}

Service provider registers a binding

Shows how AppServiceProvider wires a concrete class into the service container during the bootstrap phase, before any request is handled.

Example · php
// app/Providers/AppServiceProvider.php
public function register(): void
{
    $this->app->singleton(PaymentGateway::class, function ($app) {
        return new StripeGateway(config('services.stripe.secret'));
    });
}

Discussion

  • Be the first to comment on this lesson.