Middleware in PHP

From the Laravel cheat sheet · Controllers · verified Jul 2026

Middleware

Creating and using middleware

php
// Apply middleware to routes
Route::get('/admin', function () {
    //
})->middleware('auth', 'admin');

// Middleware groups
Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

// Controller middleware
class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('log')->only('index');
    }
}
💡 Middleware can run before and/or after request handling
⚡ Use terminable middleware for logging/cleanup after response
📌 Group middleware for applying to multiple routes
🔥 Rate limiting prevents abuse and protects APIs

More PHP tasks

Back to the full Laravel cheat sheet