I want to check which guard is logged in right now using auth sanctum
I have two tables one for users and one for students
class Student extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
in auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'student-api' => [
'driver' => 'session',
'provider' => 'students',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'students' => [
'driver' => 'eloquent',
'model' => App\Models\Student::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
```
in my controller
```
class StudentAuthController extends Controller
{
public function login(UserLoginRequest $request)
{
$data = $request->validated();
if(! Auth::guard('student-api')->attempt(['email' => $data['email'], 'password' => $data['password']])){
return response()->json(['message' => 'invalid credentials'], 403);
}
$student = Auth::guard('student-api')->user();
$token = $student->createToken('auth-student-token', ['*'])->plainTextToken;
return response()->json([
'token' => $token,
'student' => $student,
'guard-student' => Auth::guard('student-api')->user()->name
]);
}
in the previous function, I'm able to access
Auth::guard('student-api')->user();
but when I try to access it from a different endpoint I get null and please note that I have added the token in headers as I use middleware :
Route::get('/testing-student', [StudentController::class, 'test'])->middleware('auth:sanctum');
I also used this middleware and I got unauthenticated:
Route::get('/testing-student', [StudentController::class, 'test'])->middleware('auth:student-api');