Laravel 13 Middleware Explained: Create Custom Middleware Step by Step
58 people viewed this
Introduction
When developing a web application, we often need to check whether a user is authenticated, authorized, subscribed or permitted to access a particular page.
For example, consider an admin dashboard. Normal users should not be allowed to access admin-only routes.
We could write these checks inside every controller, but this creates duplicated code and makes applications difficult to maintain.
Laravel solves this problem using Middleware.
In this tutorial, you will learn how Laravel 13 middleware works, how to create custom middleware, how to register it and how to protect application routes.
1. What Is Middleware in Laravel?
Middleware is a mechanism that filters incoming HTTP requests before they reach your application's routes or controllers.
It can also process responses before they are returned to the browser.
Request Lifecycle
Browser → Middleware → Route → Controller → Response
For example:
- Authentication middleware checks whether the user is logged in.
- Authorization middleware checks user permissions.
- Custom middleware checks subscription status.
- Logging middleware records incoming requests.
Middleware helps separate request-related responsibilities from business logic.
2. Create a Laravel Project
If you don't already have a Laravel 13 project, create one:
composer create-project laravel/laravel middleware-demo
Move into the project directory:
cd middleware-demo
Start the development server:
php artisan serve
3. Create Custom Middleware
Laravel provides an Artisan command for generating middleware.
php artisan make:middleware CheckUserRole
This creates the following file:
app/Http/Middleware/CheckUserRole.php
Open the file and implement the following:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckUserRole
{
public function handle(
Request $request,
Closure $next
): Response {
if (
!$request->user() ||
$request->user()->role !== 'admin'
) {
abort(403, 'Unauthorized access.');
}
return $next($request);
}
}
How Does This Code Work?
- Laravel receives the HTTP request.
- Middleware checks whether the user exists.
- It verifies whether the user's role is admin.
- If the condition fails, Laravel returns a 403 response.
- Otherwise, the request continues to the next middleware or route.
Important: This example assumes your users table has a role column. Authentication must also be configured before relying on the authenticated user.
4. Register Middleware in Laravel 13
Modern Laravel applications configure middleware in:
bootstrap/app.php
Import the middleware class:
use App\Http\Middleware\CheckUserRole;
use Illuminate\Foundation\Configuration\Middleware;
Inside the application configuration, register an alias:
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'admin' => CheckUserRole::class,
]);
})
The alias allows you to use a short name instead of writing the complete middleware class.
5. Apply Middleware to Routes
Open routes/web.php.
use Illuminate\Support\Facades\Route;
Route::get('/admin/dashboard', function () {
return view('admin.dashboard');
})->middleware(['auth', 'admin']);
Now the route requires:
- The user must be authenticated.
- The user must have the admin role.
Apply Middleware to Route Groups
You can also apply middleware to a group:
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('/admin/dashboard', function () {
return 'Admin Dashboard';
});
Route::get('/admin/users', function () {
return 'Manage Users';
});
});
This avoids repeating middleware on every route.
6. Middleware Parameters
Sometimes you need to pass parameters to middleware.
For example, you may want to allow multiple roles.
Update the Middleware
public function handle(
Request $request,
Closure $next,
string ...$roles
): Response {
$user = $request->user();
if (!$user || !in_array($user->role, $roles, true)) {
abort(403, 'Access denied.');
}
return $next($request);
}
Pass Parameters to Middleware
Route::get('/reports', function () {
return 'Reports Page';
})->middleware('admin:admin,manager');
Now both admin and manager can access the route.
7. Real-World Middleware Use Cases
Middleware is useful in many types of applications:
| Application | Middleware Use |
|---|---|
| E-commerce | Check customer authentication |
| ERP | Verify department access |
| Pharmacy | Restrict pharmacist features |
| Billing Software | Verify subscription |
| School Management | Restrict teacher and admin routes |
| SaaS | Check tenant access |
For a larger application, consider Laravel Policies and Gates for resource-level authorization, and packages such as Spatie Laravel Permission for managing complex permissions.
8. Common Middleware Mistakes
Mistake 1: Forgetting to Register Custom Middleware Aliases
Solution: Register the alias in bootstrap/app.php.
Mistake 2: Accessing the Authenticated User Without Checking Authentication
Solution: Use the auth middleware before your custom role middleware.
Mistake 3: Repeating the Same Logic in Multiple Controllers
Solution: Move reusable request checks into middleware.
Mistake 4: Using Middleware for All Authorization Logic
Solution: Use Policies and Gates when authorization depends on a particular model or resource.
9. Best Practices
- Keep middleware focused on one responsibility.
- Avoid putting complex business logic inside middleware.
- Use meaningful middleware names.
- Apply middleware to route groups when appropriate.
- Return proper HTTP status codes.
- Test middleware for authorized and unauthorized users.
- Never trust role information submitted by the client.
Frequently Asked Questions
Q1. What is middleware in Laravel?
Middleware filters HTTP requests before they reach the application routes and can also process outgoing responses.
Q2. How do I create middleware in Laravel 13?
Run php artisan make:middleware MiddlewareName.
Q3. Where do I register middleware in Laravel 13?
Use bootstrap/app.php and the withMiddleware() configuration method.
Q4. Can we apply multiple middleware to one route?
Yes. Pass an array of middleware names to the middleware() method.
Q5. What is the difference between middleware and a controller?
Middleware handles request filtering and cross-cutting concerns. Controllers handle application request logic.
Conclusion
Middleware is one of the most important concepts in Laravel development.
By using custom middleware, you can centralize authentication checks, role verification, subscription validation and other request-related operations.
Instead of repeating conditions throughout your application, you can create reusable middleware and keep your controllers clean.
Keep Learning with Codementrix!
Official Reference: Laravel 13 Middleware Documentation
Was this useful?
No ratings yet — yours can be the first.
Discussion
Notes from readers. Comments appear after a short review.
No comments yet. Start the thread below.