Google Drive PHP API pagination not working when using different requests
P粉993712159
P粉993712159 2023-09-06 15:00:23
0
1
530

I am using Google Drive PHP API in Laravel (v9.0) project. Regarding paging, I hope to have the following process:

  1. Get the first page of the file and return it to the front end;
  2. When the user scrolls to the bottom of the page, the front end requests the next page file;
  3. The backend receives the request and gets the corresponding page from the Google Drive API.

The problem I'm facing is that when the frontend requests the next page (in the example below, pageToken has the nextPageToken value from the previous Google Drive call), Google throws Error: Code: 400, Message: Invalid value, Location: pageToken. Below is the code I'm using:

$pageToken = request()->input('pageToken');

$optParams = [
    'q' => '' . $parentQuery,
    'pageSize' => $paginateSize,
    'fields' => 'nextPageToken, files(id, name, parents)',
];

if ($pageToken) {
    $optParams['pageToken'] = $pageToken;
}

$response = $this->service->files->listFiles($optParams);

However, if I get all the pages before returning to the backend, it seems to work:

$optParams = [
    'q' => '' . $parentQuery,
    'pageSize' => $paginateSize,
    'fields' => 'nextPageToken, files(id, name, parents)',
];

$files = [];

do {
    $results = $this->service->files->listFiles($optParams);

    $files = array_merge($files, $results->getFiles());

    $pageToken = $results->getNextPageToken();

    if ($pageToken) {
        $optParams['pageToken'] = $pageToken;
    }

} while ($pageToken);

I may be misunderstanding how pagination is used in the Google Drive API, but is there a way to paginate content like in my first example?

P粉993712159
P粉993712159

reply all(1)
P粉546138344

Use the isset and empty functions to check whether the pageToken value is valid

$pageToken = request()->input('pageToken');

$optParams = [
    'q' => '' . $parentQuery,
    'pageSize' => $paginateSize,
    'fields' => 'nextPageToken, files(id, name, parents)',
];

if (isset($pageToken) && !empty($pageToken)) {
    $optParams['pageToken'] = $pageToken;
}

$response = $this->service->files->listFiles($optParams);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template