I'm working on a Laravel 11 API using Sanctum for authentication. I have a route protected by the auth:sanctum middleware, and I'm sending a valid token in the request header. However, when I try to get the authenticated user with:
// Obtener el perfil del usuario autenticado
public function getAuthenticatedUser()
{
return Auth::user();
}
public function getProfile()
{
try {
$user = $this->userService->getAuthenticatedUser();
return response()->json(['user' => $user], 200);
} catch (\Exception $e) {
return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500);
}
}
and it´s returns { "error": "Usuario no encontrado" }
on postman and on my frontend app with react.
What I've checked so far: The token exists in the personal_access_tokens table and is linked to a valid user. The middleware auth:sanctum is applied correctly to the route. I've tried running php artisan tinker and Auth::user() also returns null. Double-checked that I'm using use Illuminate\Support\Facades\Auth; (not the wrong Auth class). Possible Causes? What else should I check? Could there be an issue with my middleware configuration or token validation? Any advice would be appreciated.
Thanks in advance!