GET /account: Returns API 响应令牌

GET /account: Returns API Token on response

当用户创建新帐户时,我添加了它的 API 令牌并将其 return 编辑给用户。但是当用户查看他们的帐户信息时,我无法想 return 向用户发送 API 令牌。

GET /account: Returns API 令牌响应。

这是我的代码文件User.php:

public function index()
{
    $users = User::where('id', auth()->user()->id)->get();

    return response([
        'data' => UserResource::collection($users),
        'message' => 'Retrieve successfully'
    ], 200);
}

// POST
public function store(Request $request)
{
    $data = $request->all();

    $validator = Validator::make($data, [
        'name' => 'required|max:255|string',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|string',
    ]);

    if ($validator->fails()) {
        return response(['error' => $validator->errors(), 'Validation Error'], 400);
    }

    $users = User::create($data);

    $token = $users->createToken('accessToken')->plainTextToken;

    return response([
        'data' => new UserResource($users),
        'api_token' => $token,
        'message' => 'Created successfully'
    ], 201);
}

这是我的代码文件api.php(路线):

Route::group(['prefix' => 'v1' ], function () {

    // Account
    Route::post('/account', [UserController::class, 'store']);

    // Protected route
    Route::group(['middleware' => ['auth:sanctum']], function () {

            // Account
            Route::get('/account', [UserController::class, 'index']);
    });
});

使用$request->bearerToken()获取不记名令牌。

public function index()
{
    $users = User::where('id', auth()->user()->id)->get();

    return response([
        'data' => UserResource::collection($users),
        'api_token' => $request->bearerToken(),
        'message' => 'Retrieve successfully'
    ], 200);
}