In Laravel, middleware acts as a filter that sits between the HTTP request and your application logic.
It allows you to perform actions before or after a request is processed by the controller — such as authentication, logging, or modifying responses.
Think of middleware as a security guard that checks every request entering your Laravel app and decides whether it should proceed.
Middleware provides a convenient mechanism for filtering HTTP requests.
Laravel comes with built-in middleware such as:
auth → Ensures user authentication
guest → Redirects logged-in users away from certain pages
csrf → Protects against cross-site request forgery
throttle → Limits the number of requests per minute (rate limiting)
You can also create your own custom middleware for specific needs, like checking user roles or maintenance mode.
You can create a middleware using the Artisan command:
This command creates a new file in:
Let’s create middleware that checks the user’s age before allowing access to a route.
File: app/Http/Middleware/CheckAge.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAge
{
public function handle(Request $request, Closure $next)
{
if ($request->age < 18) {
return redirect('no-access');
}
return $next($request);
}
}
Here’s what happens:
The middleware checks the age parameter from the request.
If the age is less than 18, it redirects the user.
Otherwise, it passes the request to the next step (controller).
To make Laravel recognize your custom middleware, register it inside the app/Http/Kernel.php file.
Open: app/Http/Kernel.php
Add it to the $routeMiddleware array:
protected $routeMiddleware = [
// existing middleware
'checkAge' => \App\Http\Middleware\CheckAge::class,
];
You can apply middleware to specific routes or groups in your routes/web.php file.
use App\Http\Controllers\UserController;
Route::get('/home', [UserController::class, 'index'])->middleware('checkAge');
Route::get('/no-access', function () {
return "Access Denied! You must be 18 or older.";
});
You can also apply middleware to multiple routes at once:
Route::middleware('checkAge')->group(function () {
Route::get('/dashboard', function () {
return "Welcome to Dashboard!";
});
Route::get('/profile', function () {
return "This is your profile page.";
});
});