Set up routing for users with optional login in Sanctum
P粉741678385
2023-08-06 12:46:33
<p>Sanctum shares the middleware Auth:sanctum and it works. Take a look at this code: </p>
<pre class="brush:php;toolbar:false;">Route::middleware('auth:sanctum')->group(function () {
Route::post('/profile', [TestController::class, 'test']);
});</pre>
<p>And the controller method: </p>
<pre class="brush:php;toolbar:false;">public function test()
{
if (Auth::check()) {
return 'user';
} else {
return 'Guest';
}
}</pre>
<p>The problem is that if my route uses the "auth:sanctum" middleware, everything works fine for logged in users, but for guests I get an "Unauthorized" error. Without using this middleware, the authentication doesn't work properly and doesn't recognize if I'm logged in (always returns 'Guest'). How can I solve this problem? I want to show the user when logged in, otherwise "Guest" needs to be shown. </p>
If the user uses Sanctum for authentication, try using: auth('sanctum')->check().