Skip to main content
Laravel Basics Tutorial
CHAPTER 13 Beginner

Middleware and Request Lifecycle

Updated: May 14, 2026
25 min read

# CHAPTER 13

Middleware and Request Lifecycle

1. Introduction

We know that the Router acts as the Receptionist, and the Controller acts as the Doctor. But what if the hospital requires everyone to pass through a metal detector before they are even allowed to talk to the Receptionist? In Laravel, this security layer is called Middleware. In this chapter, we will learn how Middleware filters HTTP requests entering your application, providing a critical layer of defense and request manipulation.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the role of Middleware in the HTTP request lifecycle.
  • Apply existing middleware (like auth) to routes.
  • Create custom Middleware using Artisan.
  • Understand the difference between global and route-specific middleware.

3. Beginner-Friendly Explanation

Imagine an onion. The core of the onion is your application (the Controller and Database). To get to the core, an HTTP Request must pass through several layers of the onion. These layers are Middleware.
  • Layer 1 (CSRF Middleware): Checks if the request has a valid security token. If not, rejects it.
  • Layer 2 (Auth Middleware): Checks if the user is logged in. If not, redirects them to the login page.
  • Layer 3 (Custom Age Middleware): Checks if the user is over 18. If not, redirects them to a "Too Young" page.
If the request survives all the layers, it finally reaches the Controller.

4. Using Built-in Middleware

We have already used Middleware in Chapter 11 without fully exploring it. Laravel comes with several pre-built middlewares. The most common is auth.

Protecting a single route:

php
1
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth');

Protecting a group of routes: If you have an Admin panel with 20 pages, you don't want to type ->middleware('auth') 20 times. Group them!

php
12345
Route::middleware(['auth'])->group(function () {
    Route::get('/admin/users', [AdminController::class, 'users']);
    Route::get('/admin/settings', [AdminController::class, 'settings']);
    Route::post('/admin/delete', [AdminController::class, 'destroy']);
});

5. Creating Custom Middleware

Let's build a custom Middleware that checks if a user is an Administrator before allowing them to access a route.

Step 1: Generate the file via Artisan

bash
1
php artisan make:middleware IsAdmin

Step 2: Write the logic (app/Http/Middleware/IsAdmin.php)

php
1234567891011121314151617181920
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class IsAdmin
{
    public function handle(Request $request, Closure $next)
    {
        // Check if user is logged in AND their role is 'admin'
        if (Auth::check() && Auth::user()->role == &#039;admin') {
            // PASS: Send the request deeper into the onion (to the Controller)
            return $next($request); 
        }

        // FAIL: Kick them out to the homepage with an error
        return redirect(&#039;/')->with('error', 'You do not have Admin access.');
    }
}

6. Registering Custom Middleware (Laravel 10 and below)

*Note: In Laravel 11, routing and middleware registration changed to bootstrap/app.php.* Assuming Laravel 10 architecture, you must register a "nickname" for your middleware in app/Http/Kernel.php inside the $routeMiddleware array.
php
1234
protected $routeMiddleware = [
    &#039;auth' => \App\Http\Middleware\Authenticate::class,
    &#039;admin' => \App\Http\Middleware\IsAdmin::class, // Our new nickname
];

Now, apply it in web.php:

php
1234
// The user must pass BOTH the auth layer and the admin layer!
Route::get(&#039;/admin/dashboard', function() {
    return "Secret Admin Area";
})->middleware([&#039;auth', 'admin']);

7. Global vs. Route Middleware

  • Route Middleware: Only applies to routes where you explicitly type ->middleware('name'). (e.g., auth, admin).
  • Global Middleware: Runs on EVERY single request entering your application, no matter the route. (e.g., TrimStrings, VerifyCsrfToken). You don't want to run auth globally, or no one could view your public homepage!

8. Backend Workflow: Request Modification

Middleware doesn't just block requests; it can modify them. For example, Laravel's built-in TrimStrings middleware takes every piece of data submitted in a POST form and automatically trims blank spaces off the ends *before* the data reaches your Controller.

9. Best Practices

  • Keep Middleware Lightweight: Because Global Middleware runs on *every single click* your server processes, do not put heavy database queries inside them. It will drastically slow down your entire application.

10. Common Mistakes

  • Infinite Redirect Loops: If your auth middleware redirects failed users to /login, but you accidentally put the auth middleware ON the /login route itself... the user will be bounced back and forth infinitely until the browser crashes. Never put authentication middleware on public login routes.

11. Exercises

  1. 1. Explain the "Onion Analogy" regarding how an HTTP request travels through Middleware before reaching a Controller.

12. Coding Challenges

  • Challenge: Explain the conceptual logic of writing an AgeRestricted middleware. If a request has a parameter ?age=15, how would the handle() method block the request? What function allows the request to proceed if age=21?

13. MCQs with Answers

Question 1

What is the primary purpose of Middleware in Laravel?

Question 2

Inside a custom Middleware's handle() method, what code is executed to allow a valid request to successfully pass through to the next layer or the Controller?

14. Interview Questions

  • Q: Describe the difference between Global Middleware and Route Middleware. Provide an example of a built-in Laravel middleware that functions as Global.
  • Q: Walk me through the implementation of a custom Middleware designed to check user roles (e.g., Admin vs Standard User). How is it registered and applied to a route group?

15. FAQs

Q: Should I use Middleware or Gates for Authorization? A: Use Middleware for broad route protection (e.g., "Only Admins can enter the /admin URL"). Use Gates/Policies for fine-grained data protection (e.g., "Alice is an Admin, but she is only allowed to edit Blog Post #5, not Blog Post #6").

16. Summary

In Chapter 13, we added a robust security perimeter to our application. Middleware acts as a series of filters that inspect every HTTP request. By utilizing route groups and custom Middleware, we can enforce strict access control (like Admin-only areas) without cluttering our Controllers with repetitive if statements. This ensures our core application logic remains clean and heavily protected.

17. Next Chapter Recommendation

We can securely capture text data. But what about massive binary files like profile pictures? Proceed to Chapter 14: File Uploads and Storage in Laravel.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·