Auth::user() does not return the user if it is outside the auth:sanctum

139 Views Asked by At

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

There are 2 best solutions below

1
On

You can get the user from request:

Route::get('world', function (Request $request) {
    dd($request->user());
});
2
On

Try using middleware for these routes


// 1. App/Http/Kernel.php

protected $middlewareAliases = [
    'authSunctum' => \App\Http\Middleware\AuthSanctum::class,
];

...................

//2. App\Http\Middleware\AuthSanctum.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();
});