Authentication
Laravel 8
Laravel 9
Laravel 10
Laravel 11
Laravel 12
Unauthenticated Error in Laravel - Solutions
This error occurs when trying to access a protected route without proper authentication.
The Error
Error Message
Unauthenticated / 401 Unauthorized
Common Causes
- 1 User not logged in
- 2 Session expired
- 3 API token missing or invalid
- 4 Auth middleware applied incorrectly
- 5 Sanctum/Passport misconfiguration
Solutions
1
Check if user is authenticated in Blade
Blade
@auth
<p>Welcome, {{ auth()->user()->name }}</p>
@else
<a href="/login">Please login</a>
@endauth
2
For API requests, include Bearer token
JavaScript
fetch('/api/user', {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
});
3
Configure Sanctum for SPA authentication
ENV
// In .env
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
4
Handle unauthenticated redirect
PHP
// In app/Http/Middleware/Authenticate.php
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('login');
}
}
Need Help With Your Laravel Project?
I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.
About Hafiz
Senior Full Stack Developer. I build production software with Laravel, Filament, Vue, and AI integrations, and write about the real decisions behind shipping it.
Get in touch →