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
25
Related Errors
404
Laravel
ModelNotFoundException (404)
Thrown when a requested model instance cannot be found in the database.
PHP
Fatal Error: Uncaught Error
An unhandled Error exception was thrown that crashed the script.
Database
Unknown Column
The SQL query references a column that doesn't exist in the specified table.
Database
Access Denied for User
The database rejected the connection because the username or password is incorrect.