Problem: You have routes that should only be accessible by authenticated users, like user dashboards or profile pages.
Solution: Apply the built-in auth
middleware to your routes or route groups in routes/web.php
.
use Illuminate\Support\Facades\Route;
// Single route protection
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware('auth');
// Group protection for multiple routes
Route::middleware(['auth'])
->group(function () {
Route::get('/profile', [ProfileController::class, 'show']);
Route::get('/settings', [SettingsController::class, 'index']);
});
How It Works
The auth
middleware checks if a user is logged in. If not, it redirects them to the login page (configured via LOGIN_ROUTE
in config/auth.php
).
- Adding
->middleware('auth')
to a route ensures only authenticated users can access it. - Wrapping multiple routes in
Route::middleware(['auth'])->group(...)
DRYs up your code when protecting several routes at once.
Tip: You can customize the redirect path in app/Http/Middleware/Authenticate.php
by modifying the redirectTo()
method.
Share this article
Add Comment
No comments yet. Be the first to comment!