search

Home  >  Q&A  >  body text

Google Drive PHP API pagination not working when using different requests

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粉993712159P粉993712159451 days ago539

reply all(1)I'll reply

  • P粉546138344

    P粉5461383442023-09-07 11:36:00

    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);

    reply
    0
  • Cancelreply