0
0
Laravelframework~15 mins

Creating middleware in Laravel - Mechanics & Internals

Choose your learning style9 modes available
Overview - Creating middleware
What is it?
Middleware in Laravel is a way to filter HTTP requests entering your application. It acts like a gatekeeper that can check or modify requests before they reach your routes or controllers. Middleware can do things like check if a user is logged in, log request details, or block certain IP addresses. It helps organize code that should run before or after requests in a clean, reusable way.
Why it matters
Without middleware, you would have to repeat the same checks or actions inside every controller or route, making your code messy and hard to maintain. Middleware centralizes these common tasks, saving time and reducing errors. It also improves security and performance by stopping bad requests early. Imagine having to check if a user is logged in on every page manually — middleware automates this for you.
Where it fits
Before learning middleware, you should understand Laravel routing and controllers, as middleware works with them. After mastering middleware, you can explore advanced topics like middleware groups, custom guards, and request lifecycle events. Middleware fits into the bigger picture of Laravel's HTTP request handling.
Mental Model
Core Idea
Middleware is a filter that processes HTTP requests before they reach your application logic and can modify or block them as needed.
Think of it like...
Middleware is like a security guard at a building entrance who checks IDs and decides who can enter or what they can carry inside.
┌───────────────┐
│ HTTP Request  │
└──────┬────────┘
       │
┌──────▼───────┐
│  Middleware  │  <-- Checks, modifies, or blocks request
└──────┬───────┘
       │
┌──────▼───────┐
│ Controller / │
│   Route      │
└──────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Middleware in Laravel
🤔
Concept: Middleware acts as a filter for HTTP requests in Laravel.
Middleware runs code before or after a request hits your routes or controllers. Laravel includes some middleware by default, like checking if a user is authenticated. You can think of middleware as a layer that every request passes through.
Result
Requests can be checked or modified centrally before reaching your app logic.
Understanding middleware as a filter helps you see how Laravel organizes common request tasks cleanly.
2
FoundationHow to Create a Basic Middleware
🤔
Concept: You can create custom middleware classes to define your own request filters.
Use the artisan command `php artisan make:middleware CheckAge` to create a middleware. Then, inside the middleware class, write a handle method that receives the request and a next callback. You can check conditions and either allow the request to continue or block it.
Result
You get a reusable middleware class that can be attached to routes.
Knowing how to create middleware classes is the first step to customizing request handling.
3
IntermediateRegistering Middleware in Kernel
🤔Before reading on: Do you think middleware runs automatically after creation or needs registration? Commit to your answer.
Concept: Middleware must be registered in the HTTP kernel to be used by routes.
Open `app/Http/Kernel.php`. You can add your middleware to the `$routeMiddleware` array with a key name. This key is used to assign middleware to routes or groups. Without registration, Laravel won't know about your middleware.
Result
Middleware becomes available to assign to routes by name.
Understanding registration prevents confusion about why middleware doesn't run after creation.
4
IntermediateAssigning Middleware to Routes
🤔Before reading on: Can middleware be applied to individual routes, groups, or both? Commit to your answer.
Concept: Middleware can be attached to single routes or groups of routes for flexible filtering.
In your routes file, use the `middleware` method or array key to assign middleware by its registered name. For example, `Route::get('/profile', function(){})->middleware('auth');`. You can also group routes with middleware using `Route::middleware(['auth'])->group(function(){ ... });`.
Result
Requests to those routes pass through the assigned middleware filters.
Knowing how to assign middleware lets you control which requests get filtered and how.
5
IntermediateMiddleware Parameters and Customization
🤔Before reading on: Do you think middleware can accept parameters to change behavior? Commit to your answer.
Concept: Middleware can accept parameters to customize their behavior per route.
When assigning middleware, you can pass parameters like `->middleware('role:admin')`. Inside the middleware's handle method, you receive these parameters and can adjust logic accordingly. This makes middleware flexible and reusable for different cases.
Result
Middleware behavior can vary without creating multiple classes.
Understanding parameters unlocks powerful, reusable middleware design.
6
AdvancedMiddleware Groups and Global Middleware
🤔Before reading on: Does global middleware run on every request or only on assigned routes? Commit to your answer.
Concept: Laravel supports middleware groups and global middleware for broad or specific filtering.
Global middleware runs on every HTTP request and is listed in the `$middleware` array in Kernel.php. Middleware groups bundle multiple middleware under one name, like 'web' or 'api', to apply sets easily. This helps organize middleware for different parts of your app.
Result
You can efficiently manage middleware for many routes or the whole app.
Knowing middleware groups and global middleware helps scale filtering in large apps.
7
ExpertMiddleware Internals and Request Lifecycle
🤔Before reading on: Does middleware run before or after the controller? Can it modify the response? Commit to your answer.
Concept: Middleware wraps around the request lifecycle, running code before and after controllers, and can modify both request and response.
The handle method receives the request and a next callback. Calling `next($request)` passes control to the next middleware or controller. After that call, middleware can also modify the response before returning it. This allows middleware to act like a pipeline, processing requests and responses in order.
Result
Middleware can inspect, modify, or block requests and responses flexibly.
Understanding middleware as a pipeline clarifies how multiple middleware interact and how response modification works.
Under the Hood
Laravel's HTTP kernel maintains a stack of middleware. When a request arrives, it passes through this stack in order. Each middleware's handle method runs, receiving the request and a callback to the next middleware. Middleware can stop the chain by returning a response early or call the next middleware to continue. After the controller returns a response, middleware can modify it on the way back. This layered approach creates a pipeline that processes requests and responses systematically.
Why designed this way?
Middleware was designed to separate concerns and avoid repeating code in controllers. The pipeline pattern allows flexible composition of filters and actions around requests. Alternatives like putting all checks in controllers would lead to duplication and harder maintenance. The stack approach also allows easy insertion, removal, or ordering of middleware, making the system modular and extensible.
┌───────────────┐
│ HTTP Request  │
└──────┬────────┘
       │
┌──────▼───────┐
│ Middleware 1 │
│  handle()    │
└──────┬───────┘
       │ calls next
┌──────▼───────┐
│ Middleware 2 │
│  handle()    │
└──────┬───────┘
       │ calls next
┌──────▼───────┐
│ Controller   │
│  action()    │
└──────┬───────┘
       │ response
┌──────▼───────┐
│ Middleware 2 │
│ modifies resp│
└──────┬───────┘
       │
┌──────▼───────┐
│ Middleware 1 │
│ modifies resp│
└──────┬───────┘
       │
┌──────▼───────┐
│ HTTP Response│
└──────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does middleware automatically run after creation without registration? Commit to yes or no.
Common Belief:Once you create a middleware class, it runs automatically on all requests.
Tap to reveal reality
Reality:Middleware must be registered in the Kernel and assigned to routes or groups to run.
Why it matters:Without registration, your middleware code never executes, causing confusion and bugs.
Quick: Can middleware only run before controllers, or can it also modify responses? Commit to one.
Common Belief:Middleware only runs before the controller and cannot change the response.
Tap to reveal reality
Reality:Middleware runs both before and after the controller, allowing it to modify the response.
Why it matters:Missing this leads to underusing middleware capabilities like response modification or logging.
Quick: Can middleware parameters be passed to customize behavior? Commit to yes or no.
Common Belief:Middleware cannot accept parameters; you must write separate middleware for each case.
Tap to reveal reality
Reality:Middleware can accept parameters to adjust behavior dynamically per route.
Why it matters:Not knowing this causes unnecessary code duplication and less flexible middleware.
Quick: Does global middleware run only on assigned routes? Commit to yes or no.
Common Belief:Global middleware only runs on routes where explicitly assigned.
Tap to reveal reality
Reality:Global middleware runs on every HTTP request automatically.
Why it matters:Misunderstanding this can cause unexpected performance issues or security holes.
Expert Zone
1
Middleware order matters deeply; reversing order can break authentication or session handling.
2
Middleware can short-circuit the request by returning a response early, skipping later middleware and controllers.
3
Middleware can share data with controllers via the request object, enabling complex workflows.
When NOT to use
Middleware is not suitable for complex business logic or data transformations; use service classes or event listeners instead. Also, avoid middleware for tasks unrelated to HTTP requests, like background jobs.
Production Patterns
In production, middleware is used for authentication, logging, CORS handling, rate limiting, and maintenance mode. Middleware groups separate web and API concerns. Custom middleware often handles role-based access control and input sanitization.
Connections
Aspect-Oriented Programming (AOP)
Middleware is a practical example of AOP by injecting behavior around core logic.
Understanding middleware as AOP helps grasp how cross-cutting concerns are modularized in software.
Network Firewalls
Middleware acts like a firewall filtering requests before they reach internal systems.
Seeing middleware as a firewall clarifies its role in security and request validation.
Assembly Line Manufacturing
Middleware processing resembles an assembly line where each station adds or checks something before passing on.
This connection shows how middleware pipelines ensure orderly, stepwise processing of requests.
Common Pitfalls
#1Middleware created but not registered in Kernel.
Wrong approach:php artisan make:middleware CheckAge // Added class but forgot to add to Kernel.php
Correct approach:Add 'check.age' => \App\Http\Middleware\CheckAge::class, to $routeMiddleware in Kernel.php
Root cause:Not understanding that Laravel requires explicit middleware registration.
#2Middleware handle method missing call to next middleware.
Wrong approach:public function handle($request, Closure $next) { if ($request->age < 18) { return redirect('home'); } // Missing return $next($request); }
Correct approach:public function handle($request, Closure $next) { if ($request->age < 18) { return redirect('home'); } return $next($request); }
Root cause:Not realizing the middleware chain must continue by calling next.
#3Passing middleware parameters incorrectly as array instead of colon syntax.
Wrong approach:Route::get('/admin', function(){})->middleware(['role', 'admin']);
Correct approach:Route::get('/admin', function(){})->middleware('role:admin');
Root cause:Misunderstanding Laravel's middleware parameter syntax.
Key Takeaways
Middleware in Laravel filters HTTP requests before they reach your application logic, enabling centralized checks and modifications.
You must create, register, and assign middleware properly for it to run on your routes.
Middleware runs in a pipeline, allowing code before and after controllers, and can modify both requests and responses.
Middleware parameters and groups provide powerful ways to customize and organize request filtering.
Understanding middleware internals and order is key to building secure, maintainable Laravel applications.