Advanced LaravelExtra· 30 min read

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.)

The auth middleware protects a route
// 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:

  1. A request comes in for the protected URL (/dashboard).
  2. Before the controller runs, the auth middleware checks: is this user logged in?
  3. If yes, the request passes through to the controller and the page is shown.
  4. 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?

Answer: Middleware runs on requests — a classic use is the auth middleware, which blocks pages for users who are not logged in.

✍️ Practice

  1. Protect a route with the auth middleware.
  2. Read about another built-in middleware.

🏠 Homework

  1. Add auth protection to the create/edit/delete routes of a resource.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →