Back to Blog
Lesson 26 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Protecting Routes with Middleware: A Laravel Beginner’s Guide

Learn how to use Laravel middleware to secure your routes. We'll cover applying the auth middleware, protecting route groups, and managing redirects.

LaravelMiddlewareSecurityAuthorizationWeb Developmentphpbackend

Previously in this course, we covered introduction to authentication to scaffold our login and registration system. While our users can now sign in, our application is still wide open; anyone can visit any URL, whether they are logged in or not.

In this lesson, we are going to fix that. We'll learn how to use middleware to act as a security guard for our routes, ensuring that only authenticated users can access sensitive areas of our Task Manager app.

What is Middleware?

Think of middleware as a series of filters that an HTTP request must pass through before it reaches your controller. When a user requests a URL, the request doesn't jump straight to your code. Instead, it hits the "middleware stack."

If the request meets the requirements (e.g., the user is logged in), the middleware allows the request to continue. If it fails, the middleware stops the request and performs an action, such as redirecting the user to the login page. This is the core of security and authorization in Laravel.

Applying the 'auth' Middleware

Laravel ships with a pre-configured auth middleware. When you apply this to a route, Laravel checks the current session. If no user is authenticated, it automatically redirects the user to the login route.

To protect a single route, you can chain the middleware method directly to your route definition in routes/web.php:

PHP
use Illuminate\Support\Facades\Route;

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth');

In this example, if a guest tries to visit /dashboard, they are immediately sent to the login screen. Once they sign in, Laravel remembers their original destination and redirects them back to the dashboard.

Protecting Route Groups

Usually, you won't want to protect just one route, but an entire section of your application—like all your Task Manager pages. Instead of repeating ->middleware('auth') on every single line, we use a route group.

Open routes/web.php and wrap your task-related routes like this:

PHP
Route::middleware(['auth'])->group(function () {
    Route::get('/tasks', [TaskController::class, 'index']);
    Route::get('/tasks/create', [TaskController::class, 'create']);
    Route::post('/tasks', [TaskController::class, 'store']);
});

By grouping these routes, you ensure that every endpoint inside the group closure is protected by the auth middleware. If you add a new route to this group later, it is automatically secured.

Hands-on Exercise: Securing the Task Manager

Right now, your users can visit the task list even if they aren't logged in. Let's lock it down.

  1. Open routes/web.php.
  2. Locate the routes that define your task management functionality.
  3. Wrap these routes in a Route::middleware(['auth'])->group(function () { ... }) block.
  4. Navigate to your application in the browser while logged out and try to access /tasks. You should be redirected to the login page.
  5. Log in, and verify that you can now access the task list successfully.

Common Pitfalls

Even for experienced developers, middleware can occasionally cause confusion. Here are the most common traps:

  • Forgetting the Login Route: Laravel's auth middleware looks for a route named login. If you haven't defined one (or if you've renamed it), your app will throw an error when a guest is redirected. Ensure your authentication starter kit is fully set up.
  • Applying Middleware to the Login Route: Never put your login or registration routes inside an auth group. If you do, you'll create an infinite redirect loop because the user needs to be authenticated to reach the page that authenticates them!
  • Middleware Order: While rarely an issue for beginners, remember that middleware is executed in the order it is listed. If you have custom middleware that depends on the user being logged in, it must be placed after the auth middleware in the stack.

Recap

Middleware provides a clean, declarative way to enforce security across your application. By using the auth middleware, you offload the complex logic of session checking and redirection to Laravel's robust core.

We've successfully moved from a public-facing application to one that respects user identity. We've used groups to keep our route file clean and ensured that our sensitive task data is only visible to logged-in users.

Up next: We'll dive into Understanding CSRF Protection to ensure that the forms submitting your tasks are secure and originate from your own site.

Similar Posts