Middleware
Run code on requests — for authentication, logging and more.
What you will learn
- Understand middleware
- Protect routes
- Apply middleware
Filter requests
Middleware runs before (or after) your controller — perfect for checking “is the user logged in?” before showing a page. (Same idea as Express middleware, if you saw the Node course.)
// protect a route — only logged-in users
Route::get('/dashboard', [DashboardController::class, 'index'])
->middleware('auth');The ->middleware('auth') added to the route is the whole trick. It attaches Laravel’s built-in auth middleware, which runs before the controller. If the visitor is logged in, the request continues to DashboardController@index as normal. If not, the auth middleware stops the request and redirects them to the login page — the dashboard code never even runs.
The request path with middleware in place:
- A request comes in for the protected URL (
/dashboard). - Before the controller runs, the
authmiddleware checks: is this user logged in? - If yes, the request passes through to the controller and the page is shown.
- If no, the middleware blocks it and redirects the user to the login page.
Note: Laravel ships with useful middleware (auth, guest, throttling). You can also generate your own with php artisan make:middleware for custom checks.
Q. What is middleware commonly used for?
✍️ Practice
- Protect a route with the
authmiddleware. - Read about another built-in middleware.
🏠 Homework
- Add auth protection to the create/edit/delete routes of a resource.