How do I share a file to a specific folder using Google Drive API?

Viewed 62

I did the code below and I tried to use 'parents' to share a file to a specific folder, but it didn't work. I looked everywhere for a solution, but I can't find any.

function grantPermission($role, $user, $atividade){
    $userPermission = new Google_Service_Drive_Permission(array(
        'type' => 'user',
        'role' => $role,
        'emailAddress' => $user->email,
        'parents' => array($user->folder_id_minhas_atividades),
    ));

    $request = $this->drive->permissions->create($atividade->folder_id, $userPermission, array('fields' => 'id'));
    
    $ret = redirect()->route('verAtividade.verPessoas', ['atividade_id' => $atividade->id]);
    return $ret;
}
1 Answers

If you share a file with a user, this file will remain in your Drive

The user will only see it as "Shared with me", but not in a folder on his Drive.

For what you are trying to achieve you need to update the parents of the file instead of changing the permissions.

Provided you move the file to a folder on a user's Drive - the user will automatically obtain access permissions for the file.

Use the method Files: update and pass to the parameter addParents the folder id.

Sample:

$driveService = new \Google_Service_Drive($this->client);
$file = $driveService->files->update($fileId, $emptyFileMetadata, array(
    'addParents' => $folderId
));

Depending on the situation you might also need to specify in the request body 'removeParents' => $previousParents.

Related