How to Use Auth Middleware in Laravel for Route Protection
In Laravel, use the
auth middleware to protect routes by adding it to your route or controller. This middleware checks if a user is logged in and redirects guests to the login page automatically.Syntax
The auth middleware is applied to routes or controllers to restrict access to authenticated users only. You can add it using the middleware method on routes or in the controller constructor.
- Route syntax:
Route::get('/dashboard', function () {})->middleware('auth'); - Controller syntax:
public function __construct() { $this->middleware('auth'); }
php
Route::get('/dashboard', function () { return view('dashboard'); })->middleware('auth');
Example
This example shows how to protect a route named /dashboard so only logged-in users can access it. Guests will be redirected to the login page automatically.
php
<?php use Illuminate\Support\Facades\Route; Route::get('/dashboard', function () { return 'Welcome to your dashboard!'; })->middleware('auth');
Output
If user is logged in: "Welcome to your dashboard!"
If not logged in: Redirects to /login page
Common Pitfalls
- Forgetting to add the
authmiddleware to routes or controllers leaves them unprotected. - Not setting up authentication scaffolding or guards properly causes middleware to fail.
- Using
authmiddleware on API routes without configuring API guards can cause unexpected redirects.
Always ensure your authentication system is configured and that you apply auth middleware where needed.
php
/* Wrong: Route without auth middleware */ Route::get('/dashboard', function () { return 'Dashboard visible to everyone'; }); /* Right: Route protected by auth middleware */ Route::get('/dashboard', function () { return 'Dashboard visible only to logged-in users'; })->middleware('auth');
Quick Reference
Use this cheat sheet to quickly apply auth middleware in Laravel:
| Action | Code Example | Description |
|---|---|---|
| Protect a single route | Route::get('/profile', fn() => 'Profile')->middleware('auth'); | Only logged-in users can access this route. |
| Protect multiple routes | Route::middleware('auth')->group(function () { Route::get('/dashboard', fn() => 'Dashboard'); Route::get('/settings', fn() => 'Settings'); }); | Group routes under auth middleware. |
| Protect controller | public function __construct() { $this->middleware('auth'); } | Apply auth middleware to all controller methods. |
| Redirect guests | Handled automatically by auth middleware | Guests are redirected to login page if not authenticated. |
Key Takeaways
Add
auth middleware to routes or controllers to restrict access to logged-in users.Guests are automatically redirected to the login page when accessing protected routes.
Ensure your authentication system is properly set up for the middleware to work correctly.
Use route groups to apply
auth middleware to multiple routes easily.Avoid leaving sensitive routes unprotected by forgetting to add the middleware.