PHP: Fetching only root-level folders from Google Drive API

I’m working on a project where I need to show users a list of folders from their Google Drive, but only the ones in the root directory. They should be able to pick a folder for uploading files or choose the root itself.

I’ve got the Google Drive API set up, but I’m not sure how to filter the results to show only root-level folders. Here’s what I’ve got so far:

$service = new Google_Service_Drive($client);
$parameters = array();
$files = $service->files->listFiles($parameters);

Can I add some kind of query to the $parameters array to get just the folders I want? Or is there a better way to do this?

I’d really appreciate any help or tips on how to make this work. Thanks!

I’ve implemented a similar feature in a recent project. Here’s an approach that worked well for me:

$parameters = array(
‘q’ => “‘root’ in parents and mimeType = ‘application/vnd.google-apps.folder’”,
‘fields’ => ‘nextPageToken, files(id, name)’,
‘pageSize’ => 100
);

$results = $service->files->listFiles($parameters);

This query fetches root-level folders efficiently. The ‘pageSize’ parameter limits results per request, which is useful when dealing with larger drives. You might also want to add error handling:

try {
$folders = $results->getFiles();
} catch (Exception $e) {
// Handle API errors here
}

Remember to respect API usage limits and implement proper authentication flows for production use.

hey there! i’ve dealt with this before. you can use the ‘q’ parameter in your $parameters array to filter for root folders. try something like this:

$parameters = array(
‘q’ => “‘root’ in parents and mimeType = ‘application/vnd.google-apps.folder’”
);

this should give you just the folders in the root. hope it helps!

I’ve implemented something similar in one of my projects. To fetch only root-level folders, you can indeed use the ‘q’ parameter as suggested, but I’d recommend adding a few more parameters for efficiency:

$parameters = array(
‘q’ => “‘root’ in parents and mimeType = ‘application/vnd.google-apps.folder’”,
‘fields’ => ‘files(id, name)’,
‘orderBy’ => ‘name’
);

This query will return only the necessary fields (id and name) for root folders, sorted alphabetically. It’s more efficient as it reduces the amount of data transferred.

Also, don’t forget to handle pagination if there are many folders:

$results = $service->files->listFiles($parameters);
$folders = $results->getFiles();

while ($results->getNextPageToken()) {
$parameters[‘pageToken’] = $results->getNextPageToken();
$results = $service->files->listFiles($parameters);
$folders = array_merge($folders, $results->getFiles());
}

This ensures you get all folders, even if they span multiple pages.