Middleware
Middleware filters HTTP requests entering your application.
Syntax
public function handle($request, Closure $next) { ... }Middleware wraps around your request handling — perfect for authentication, logging, or CORS. Each middleware can inspect the request and either pass it along with $next($request) or stop it.
Generate one with php artisan make:middleware EnsureTokenIsValid.
Example
namespace App\Http\Middleware;
use Closure;
class EnsureTokenIsValid
{
public function handle($request, Closure $next)
{
if ($request->input('token') !== 'secret') {
return redirect('/login');
}
return $next($request);
}
}When to use it
- An admin panel applies the 'auth' middleware to all routes inside the /admin prefix so unauthenticated requests are redirected to the login page automatically.
- A multi-tenant application uses a custom middleware to resolve the tenant from the subdomain and bind it in the container before any controller runs.
- A rate-limiting middleware throttles the public API to 60 requests per minute, returning a 429 response automatically when the limit is exceeded.
More examples
Generate and register a middleware
Artisan generates the middleware file with a handle() stub; you then register it in app/Http/Kernel.php before using it on routes.
php artisan make:middleware EnsureTokenIsValid
# Creates app/Http/Middleware/EnsureTokenIsValid.phpWrite a middleware handle method
The handle() method inspects the request and either returns an error response early or calls $next($request) to continue the pipeline.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnsureTokenIsValid
{
public function handle(Request $request, Closure $next): mixed
{
if ($request->input('token') !== config('app.api_token')) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request); // pass to the next layer
}
}Apply middleware to route groups
Applies named middleware to individual routes or groups; parameterised middleware like 'role:admin' passes 'admin' as the second argument to handle().
// Single route
Route::get('/secret', SecretController::class)
->middleware('auth');
// Route group
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/dashboard', DashboardController::class);
Route::resource('/posts', PostController::class);
});
// Parameterised middleware
Route::get('/admin', AdminController::class)
->middleware('role:admin');
Discussion