'Laravel sanctum check if user is authenticated

How to check if the user is authenticated when using Laravel sanctum?

Example :

Controller :

public function testAuth(Request $request)
{ 
     if ($request->user()) {
            return "auth";
      } else {
            return "guest";
      }
}

api.php

Route::get('testauth', [MyTestController::class, 'testAuth']);

this route always returns guest even if I pass token in headers.

when I add sanctum middleware, route return auth

api.php

Route::get('testauth', [MyTestController::class, 'testAuth'])->middleware('auth:sanctum');

but I don't want that , I want to check if the user is authenticated in the controller without using middleware



Solution 1:[1]

Try this following code will help you.....You can use user('sanctum') instead of user()

public function testAuth(Request $request)
{ 
     if ($request->user('sanctum')) {
            return "auth";
      } else {
            return "guest";
      }
}

Solution 2:[2]

first attach auth middleware with sanctum guard like this to route

Route::get('/somepage', 'SomeController@MyMethod')->middleware('auth:sanctum');

Then inside route closure/controller action access it with

auth()->user()

as usual

authorization http header must hold your bearer token

Solution 3:[3]

if (auth('sanctum')->check()){
   return "auth";
}else{
   return "guest";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manikandan G
Solution 2 Asd
Solution 3 d3ridi