I'm using Laravel Sanctum to authenticate users. I'd like to have a route that can be accessed by guests and logged in users. Logged in users send an API Token in the Authorization header.
I've tried making a route without authentication, but that way I can't see the logged in user.
Route::get('noauth', function() {
return Auth::check();
});
GET /noauth with auth header returns false, user is not logged in
GET /noauth without auth header returns false, user is not logged in
I've also tried using auth:sanctum
middleware, but that way guests can't access the page.
Route::get('yesauth', function() {
return Auth::check();
})->middleware('auth:sanctum');
GET /yesauth with auth header returns true, the user is logged in
GET /yesauth withouth auth header returns 401, unauthorized
The solution should return true with auth headers, and false without auth headers.
return Auth::guard('web')->check();
for me?Auth::guard('api')
returns errors.auth('sanctum')->user()
, you can get the user. It will return null if the user is not logged in. `Auth::guard('sanctum')->user()
worked with me.