search

Home  >  Q&A  >  body text

Set up routing for users with optional login in Sanctum

<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>
P粉741678385P粉741678385466 days ago507

reply all(1)I'll reply

  • P粉517814372

    P粉5178143722023-08-07 09:40:16

    If the user uses Sanctum for authentication, try using: auth('sanctum')->check().

    reply
    0
  • Cancelreply