Middleware in Laravel acts as a bridge between a request and a response. It provides a convenient mechanism for filtering HTTP requests entering your application. Whether verifying a user is authenticated, logging the request, or modifying headers, middleware is crucial in Laravel’s request lifecycle.
In Laravel, middleware is essential because it helps you encapsulate logic that should be applied to a group of routes or every request. Middleware makes your application more organized and secure, from built-in functionalities like CSRF protection to custom logic for role checking.

Laravel’s built-in middleware system is robust and easy to extend. It includes global middleware that applies to all requests, route-specific middleware, and grouped middleware for managing complex stacks.
In this article, you’ll learn how to use middleware in Laravel, including its types, how to create and apply custom middleware, and everyday use cases like authentication and logging—all with best practices for clean, efficient code.
Types of Middleware in Laravel
Laravel provides different types of middleware to handle HTTP requests efficiently. Each type serves a unique purpose—some run globally on every request, while others apply only to specific routes or groups. Understanding these types helps you organize your application and apply logic exactly where needed.
Global Middleware
Global middleware is executed for every HTTP request that enters your Laravel application. It is typically used for tasks that must always be performed, such as trimming input strings, handling proxies, or verifying CSRF tokens.
These are registered in the $middleware
array of the app/Http/Kernel.php
file.
Examples:
\Illuminate\Foundation\Http\Middleware\TrimStrings
\App\Http\Middleware\VerifyCsrfToken
Route Middleware
Route middleware is assigned to specific routes or route groups. It’s used to apply checks or logic only where needed, such as requiring authentication or restricting access to guests.
These are registered in the $routeMiddleware
array of the app/Http/Kernel.php
file.
Examples:
'auth' => \App\Http\Middleware\Authenticate::class
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class
Middleware Groups
Middleware groups allow you to bundle multiple middleware under a single key to simplify route definitions. These are useful for applying a standard set of middleware, like those needed for web or API routes.
They are defined in the $middlewareGroups
array in the app/Http/Kernel.php
file.
Examples:
'web' => [\App\Http\Middleware\EncryptCookies::class, ...]
'api' => ['throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class]
Custom Middleware
Custom middleware is user-defined and created to handle specific application logic that doesn’t come out of the box with Laravel, such as checking user roles or blocking particular IPs.
Created using Artisan and registered in Kernel.php
, either globally or as route middleware.
Examples:
php artisan make:middleware CheckIfAdmin
\App\Http\Middleware\CheckIfAdmin::class
Check Out | RAID Explained: Understanding RAID 0, 1, 5, and 10 for Beginners
Create and Register Custom Middleware in Laravel
Creating custom middleware in Laravel allows you to define and apply your request-handling logic, such as checking user roles, blocking IPs, or modifying request data. It helps keep your code clean and reusable by isolating specific functionality from controllers or routes.
Steps to Create Custom Middleware in Laravel:
- Create the Middleware Class
Use the Artisan command to generate a new middleware file:
php artisan make:middleware CheckIfAdmin
This creates a file at app/Http/Middleware/CheckIfAdmin.php
.
- Define the Logic in
handle()
Method
Open the newly created file and implement your custom logic using the handle()
technique. Use $next($request)
to continue the request lifecycle.
public function handle($request, Closure $next)
{
if (!auth()->check() || !auth()->user()->isAdmin()) {
return redirect('/home');
}
return $next($request);
}
Register the Middleware
To use your middleware, register it in app/Http/Kernel.php
.
- As Route Middleware (recommended):
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\CheckIfAdmin::class,
];
- As Global Middleware (less common):
protected $middleware = [
\App\Http\Middleware\CheckIfAdmin::class,
];
Apply Middleware to Routes
Once registered, apply it to routes or controllers.
- Single Route:
Route::get('/admin', function () {
// Admin dashboard
})->middleware('admin');
- Controller Constructor:
public function __construct()
{
$this->middleware('admin');
}
Testing Your Middleware
Finally, testing your middleware to confirm it behaves correctly is essential. You can do this by:
- Logging in with a non-admin account and trying to access the protected route to verify it redirects as intended.
- Logging in with an admin account to ensure the route is accessible without any issues.
Use Middleware in Laravel with Example
After creating and registering middleware, the next step is to apply it where needed in your application. Laravel allows you to use middleware on individual routes, route groups, or within controller constructors. This helps control access or behavior based on request conditions.
- Apply Middleware to a Single Route
You can apply middleware directly to a route using the middleware()
method:
Route::get('/admin', function () {
return view('admin.dashboard');
})->middleware('admin');
The admin
middleware will run before granting access to the /admin
route.
- Apply Middleware to Route Groups
If multiple routes share the same middleware, group them:
Route::middleware(['admin'])->group(function () {
Route::get('/admin', 'AdminController@index');
Route::get('/admin/settings', 'AdminController@settings');
});
All routes in this group will pass through the admin
middleware.
- Apply Middleware in Controller Constructor
You can also use middleware inside a controller’s constructor:
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('admin');
}
public function index()
{
// Admin dashboard
}
}
This applies to the admin
middleware for all methods in the controller, keeping your route file clean.
Common Use Cases for Middleware
Middleware in Laravel helps handle application-wide concerns that affect incoming HTTP requests. Here are some of the most common scenarios where middleware is used:
CSRF Protection
The VerifyCsrfToken
Middleware is used to protect applications from cross-site request forgery attacks. It ensures that any form submissions or POST requests include a valid CSRF token. This middleware is part of Laravel’s default web
middleware group and is automatically applied to most web routes.
Logging and Monitoring
Middleware can log incoming requests, track user activity, or monitor performance. For example, it can record the full URL of each request, headers, and IP addresses. This is useful for maintaining server logs, analyzing traffic, or troubleshooting issues in the application.
You can create a middleware to log every request or certain types of data:
\Log::info('Request Logged:', ['url' => $request->fullUrl()]);
Caching
Middleware can be used to return cached responses for specific requests, especially API endpoints or pages that don’t change frequently. By doing so, the application avoids reprocessing the same request multiple times, improving performance and reducing server load.
Localization
Middleware can automatically detect and set the application’s language based on the user’s browser settings or location. This allows Laravel to serve content in the appropriate language without requiring the user to select their preference manually.
You can use middleware to detect and set the application’s locale based on the user’s preferences or location.
app()->setLocale($request->getPreferredLanguage(['en', 'fr', 'es']));
Conclusion
Middleware in Laravel is a powerful way to filter and manage HTTP requests before they reach your core application logic. Whether using built-in middleware like authentication or CSRF protection, or creating custom ones for specific needs like role checks or localization, middleware helps you build cleaner, more maintainable, and secure applications. To dive deeper, check out the official Laravel middleware documentation.