How to Implement Middleware in Laravel
Middleware is one of Laravel’s most elegant tools for filtering and shaping HTTP requests. Let’s dive deep into how it works, and how to use it effectively.
What is Middleware in Laravel?
Middleware in Laravel acts like a security guard standing at the gate between a user’s request and your application’s logic.
It can allow, modify, or reject incoming HTTP requests before they reach your controllers — and even shape the outgoing responses.
Think of middleware as a series of layers: each layer can perform checks (like authentication or throttling),
attach additional data to the request, or modify headers. Laravel comes with several built-in middleware,
such as Authenticate, EncryptCookies, and VerifyCsrfToken.
Step 1: Creating a Custom Middleware
To create your own middleware, use Laravel’s Artisan command-line tool:
php artisan make:middleware CheckAge
This generates a new file at app/Http/Middleware/CheckAge.php.
Step 2: Writing Middleware Logic
Open the generated file and implement your logic inside the handle method. Here’s an example:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckAge
{
public function handle(Request $request, Closure $next): Response
{
if ($request->age < 18) {
return redirect('home')->with('error', 'Access denied. You must be 18 or older.');
}
return $next($request);
}
}
This middleware checks whether the request contains an age parameter less than 18.
If it does, the user is redirected; otherwise, the request continues through the pipeline.
Step 3: Registering Middleware
Next, register your middleware in the app/Http/Kernel.php file. You can register it globally or assign it to specific routes.
Global Middleware
To apply the middleware to every request, add it to the $middleware array:
protected $middleware = [
// Other middleware...
\App\Http\Middleware\CheckAge::class,
];
Route Middleware
If you only want to apply it to certain routes, add it to the $routeMiddleware array instead:
protected $routeMiddleware = [
'check.age' => \App\Http\Middleware\CheckAge::class,
];
Step 4: Applying Middleware to Routes
To apply the middleware, use the middleware() method in your routes (usually in routes/web.php):
use Illuminate\Support\Facades\Route;
Route::get('/restricted', function () {
return 'You are old enough to view this content!';
})->middleware('check.age');
Now, try visiting /restricted?age=15 — it should redirect you. At /restricted?age=20, you’ll see the message directly.
Step 5: Middleware Groups
Laravel supports middleware groups, which are useful for grouping related middleware under one alias.
For example, the web group contains middleware for session management, CSRF protection, and more.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\CheckAge::class, // Custom middleware added here
],
];
Second Example: Creating a Custom Logging Middleware
Let’s explore another example: a middleware that logs every incoming request to a custom file for auditing purposes.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class LogRequests
{
public function handle(Request $request, Closure $next): Response
{
Log::info('Incoming Request', [
'url' => $request->fullUrl(),
'ip' => $request->ip(),
'method' => $request->method(),
'user_agent' => $request->userAgent(),
]);
return $next($request);
}
}
This middleware uses Laravel’s Log facade to write request details to the log file (typically stored in storage/logs/laravel.log).
To register it, add this line inside $routeMiddleware in Kernel.php:
'log.requests' => \App\Http\Middleware\LogRequests::class,
Then apply it to routes like so:
Route::middleware(['log.requests'])->group(function () {
Route::get('/dashboard', function () {
return 'Dashboard page logged successfully.';
});
});
Advanced Concepts: Before and After Middleware
Middleware can modify the request before it reaches the controller (pre-processing)
or modify the response after the controller has handled it (post-processing).
For example, you could add headers or modify the JSON output before sending it to the client.
public function handle(Request $request, Closure $next): Response
{
// Pre-processing logic
$response = $next($request);
// Post-processing logic
$response->headers->set('X-Custom-Header', 'LaravelPro');
return $response;
}
This flexibility makes middleware extremely powerful for cross-cutting concerns
like caching, localization, security headers, or content compression.
Conclusion
Middleware in Laravel provides a clean and modular way to manage the flow of HTTP requests and responses.
Whether you’re validating input, logging activity, checking permissions, or injecting custom headers,
middleware keeps these tasks organized and reusable.
For more in-depth reading, visit the official documentation:
Laravel Middleware Documentation
.
Need to build a Website or Application?
Since 2011, Codeboxr has been transforming client visions into powerful, user-friendly web experiences. We specialize in building bespoke web applications that drive growth and engagement.
Our deep expertise in modern technologies like Laravel and Flutter allows us to create robust, scalable solutions from the ground up. As WordPress veterans, we also excel at crafting high-performance websites and developing advanced custom plugins that extend functionality perfectly to your needs.
Let’s build the advanced web solution your business demands.