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
CodePudding user response:
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";
}
}
CodePudding user response:
if (auth('sanctum')->check()){
return "auth";
}else{
return "guest";
}