AuthenticationException (401)
The user is not authenticated and cannot access the requested resource.
Explanation
AuthenticationException is thrown when a protected route or action is accessed without proper authentication. Laravel throws this when the auth() helper returns null or when using the auth:sanctum, auth:api, or auth:web middleware and the user is not logged in. For web routes, Laravel redirects to the login page. For API routes, it returns a 401 Unauthorized JSON response. This can also happen when session cookies expire or when API tokens are invalid or expired.
Common Causes
- User not logged in
- Session expired
- Invalid or expired API token
- Wrong auth middleware applied
- Cookie domain mismatch
Solution
Check that the user is logged in before accessing protected routes. For web applications, ensure the session is active and the user hasn't been logged out. For API authentication, verify that the token is valid and not expired. Use the auth()->check() method to conditionally check authentication status. For Sanctum, ensure the token has the correct abilities. Configure the LOGIN_URL in your auth config if the redirect is going to the wrong page.
Code Example
// Route requiring authentication
Route::middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/profile', [ProfileController::class, 'show']);
});
// API route with Sanctum
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', fn() => auth()->user());
});
// Manual auth check in controller
public function update(Request $request)
{
if (!auth()->check()) {
return response()->json(['message' => 'Unauthenticated'], 401);
}
// Process update
}
// Custom redirect for unauthenticated users
// In Authenticate middleware
protected function redirectTo($request)
{
return $request->expectsJson() ? null : route('login');
}
Error Information
Language
php
Framework
laravel
Difficulty
Beginner
Views
26
Related Errors
Laravel
Laravel Queue Connection Failed
The application cannot connect to the queue driver (Redis, SQS, database, etc.).
Database
Lock Wait Timeout Exceeded
A database query waited too long for a lock held by another transaction.
Database
Database Connection Refused or Timeout
The database server is not reachable or took too long to respond.
PHP
Parse Error: Syntax Error
PHP detected a syntax error in the source code that prevents parsing.