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. 1 User not logged in
  2. 2 Session expired
  3. 3 API token missing or invalid
  4. 4 Auth middleware applied incorrectly
  5. 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.

Currently available for 2-3 new projects

Hafiz Riaz

About Hafiz

Full Stack Developer from Italy. I build web applications with Laravel and Vue.js, and automate business processes. Creator of ReplyGenius, StudyLab, and other SaaS products.

View Portfolio

Related Errors