Learn how to use Laravel middleware to secure your routes. We'll cover applying the auth middleware, protecting route groups, and managing redirects.
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.
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.
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:
PHPuse 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.
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:
PHPRoute::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.
Right now, your users can visit the task list even if they aren't logged in. Let's lock it down.
routes/web.php.Route::middleware(['auth'])->group(function () { ... }) block./tasks. You should be redirected to the login page.Even for experienced developers, middleware can occasionally cause confusion. Here are the most common traps:
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.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!auth middleware in the stack.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.
Learn how to secure your Laravel Task Manager by associating tasks with users and filtering data so users can only view and manage their own personal tasks.
Read moreStop Cross-Site Request Forgery (CSRF) in its tracks. Learn how the @csrf directive works, why it's vital for your forms, and how to manage token expiration.
Protecting Routes with Middleware
Introduction to Route Model Binding
Updating Existing Records
Deleting Records
Using Named Routes
Task Manager: Completing CRUD Functionality
Introduction to Database Relationships
Querying Related Data
Handling File Uploads
Using Flash Messages for User Feedback
Task Manager: Adding Status and Priorities
Introduction to Artisan Commands
Debugging with Laravel Tinker
Understanding Service Providers
Using View Composers
Task Manager: Refactoring for Clean Code
Introduction to Testing
Testing Forms and Validation
Using Database Transactions
Handling Global Exceptions
Preparing for Production
Environment Security Best Practices
Managing Assets in Production
Task Manager: Deployment Preparation