Protecting Routes with Middleware
Use auth and guest middleware to secure routes and redirect users.
Protecting Routes with Middleware is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is Middleware?
Middleware is code that runs before or after an HTTP request reaches the controller. It is used for authentication, logging, CORS, rate limiting, etc.
Built-in auth Middleware
The auth middleware redirects unauthenticated users to the login page (or returns 401 for API requests).
<?php
Route::get("/dashboard", [DashboardController::class, "index"])
->middleware("auth");Applying Middleware to Groups
Protect an entire group of routes at once.
<?php
Route::middleware(["auth", "verified"])->group(function () {
Route::get("/dashboard", [DashboardController::class, "index"]);
Route::get("/profile", [ProfileController::class, "show"]);
});guest Middleware
The guest middleware redirects authenticated users away from login/register pages.
<?php
Route::middleware("guest")->group(function () {
Route::get("/login", [LoginController::class, "create"]);
Route::get("/register", [RegisterController::class, "create"]);
});Creating Custom Middleware
Generate with Artisan and implement the handle() method.
$ php artisan make:middleware EnsureSubscribedCustom Middleware Logic
Return the next request to continue, or return a response to abort.
<?php
public function handle(Request $request, Closure $next): Response
{
if (!$request->user()?->isSubscribed()) {
return redirect("/subscribe");
}
return $next($request);
}Registering Middleware
Register middleware aliases in app/Http/Kernel.php (Laravel 10) or bootstrap/app.php (Laravel 11+).
<?php
// Laravel 11+ bootstrap/app.php:
->withMiddleware(function (Middleware $m) {
$m->alias(["subscribed" => EnsureSubscribed::class]);
})Middleware Parameters
Pass parameters to middleware using a colon.
<?php
Route::middleware("role:admin")->group(function () {
// ...
});
// In middleware handle():
public function handle(Request $request, Closure $next, string $role): ResponseAfter Middleware
Code after $next($request) runs after the response is generated — useful for logging and response modification.
<?php
public function handle(Request $request, Closure $next): Response
{
$response = $next($request); // controller runs here
$response->headers->set("X-App", "Laravel");
return $response;
}Middleware Priority
The order middleware runs matters. Global middleware (like TrimStrings) runs before route middleware.
Throttle Middleware
Laravel includes rate limiting via the throttle middleware.
<?php
Route::middleware("throttle:60,1")->group(function () {
// 60 requests per 1 minute
});Summary
Middleware filters HTTP requests. Apply auth to protect routes, create custom middleware for business rules, and group routes to share middleware cleanly.
Quick Check
What does the auth middleware do for unauthenticated users?
Frequently asked questions
Is the “Protecting Routes with Middleware” lesson free?
Yes — the full text of “Protecting Routes with Middleware” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Protecting Routes with Middleware”?
Use auth and guest middleware to secure routes and redirect users. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Protecting Routes with Middleware” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Authentication with Laravel Breeze
- Protecting Routes with Middleware
- Gates: Simple Authorization Checks
- Policies: Model-Based Authorization