skip to Main Content

I’m creating an application using React and Laravel (Sanctum). Checking whether a user is logged in or returning user data works very well, but only within the auth:sanctum middleware. The problem is that in that case, the route won’t work properly for non-logged-in users. However, I want to check if the user is logged in from the controller level and perform a certain action based on that. The example below illustrates what I’m talking about:

Route::middleware('auth:sanctum')->group(function () {

    Route::get('hello', function () {
        dd(Auth::user()); // it displays user information
    });
});
Route::get('world', function () {
    dd(Auth::user()); // it displays null
});

This is just an example. I also tried using, for example, auth('sanctum')->check(), but every time I attempt to check if the user is logged in outside the middleware, I get false or null.

Checking if the user is logged in from the middleware level also doesn’t work because if the user is not logged in, I receive a 401 error.

In summary, I want the specific route to be accessible for both logged-in and non-logged-in users, but to display slightly different information. Therefore, I need to check if the user is logged in. How can I do this, considering what I wrote above?

2

Answers


  1. You can get the user from request:

    Route::get('world', function (Request $request) {
        dd($request->user());
    });
    
    Login or Signup to reply.
  2. Try using middleware for these routes

    
    // 1. App/Http/Kernel.php
    
    protected $middlewareAliases = [
        'authSunctum' => AppHttpMiddlewareAuthSanctum::class,
    ];
    
    ...................
    
    //2. AppHttpMiddlewareAuthSanctum.php
    
    class AuthSanctum
    {
        public function handle(Request $request, Closure $next)
        {
            if ($request->bearerToken()) {
                Auth::setUser(
                    Auth::guard('sanctum')->user()
                );
            }
    
            return $next($request);
        }
    }
    
    ..................
    3. // api.php
    
    Route::middleware('authSunctum')->group(function () {
        Route::get('world', function () {
            dd(Auth::user());
        })->middleware();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search