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
You can get the user from request:
Try using middleware for these routes