Middleware in Laravel acts as a bridge between a request and a response. It allows you to perform filtering, validation, modification, and redirection logic before or after the request hits your application logic.
In this blog post, we’ll explain what middleware is, how to use built-in middleware, how to create your own, and how to register and apply middleware in Laravel 12 — step by step.
📌 What is Middleware in Laravel?
Middleware are like filters for HTTP requests. They allow you to:
- Check authentication
- Log request data
- Apply rate limiting
- Modify headers
- Redirect unauthenticated users
- Block requests under certain conditions
For example, you can block users under 18 years old or redirect unauthenticated users to the login page.
🧰 Step 1: Use Built-In Middleware
Laravel provides many built-in middleware such as:
Middleware | Purpose |
---|---|
auth |
Ensures the user is authenticated |
guest |
Ensures the user is a guest |
verified |
Ensures email verification |
throttle |
Limits request rate (e.g. APIs) |
csrf |
Protects against CSRF attacks |
This route is accessible only if the user is authenticated.
✨ Step 2: Create Custom Middleware
To create your own middleware, use the Artisan command:
This creates a new file at:
📝 Step 3: Write Logic in Middleware
Open the newly created file and add your custom logic. Here’s how you might block users under age 18:
🗂️ Step 4: Register Middleware
Laravel 12 removes Kernel.php
and replaces it with ->withMiddleware()
registration in bootstrap/app.php
.
Locate this section in bootstrap/app.php
:
➕ Add your custom middleware as an alias: