I was stuck with this problem as well. I was trying to connect Google Drive with my Laravel project. My goal was to allow users to connect their Google Drive accounts so they can upload, download, and view a list of their files directly from the application.
To get the class :
remove the "_" and replace it with "\"
use Google_Client;
use Google\Service\Drive;
use Google\Client;
function listFiles($clientId)
{
$clientId = (int) $clientId;
$client = $this->getClient($clientId);
$service = new \Google\Service\Drive($client);
$files = $service->files->listFiles([
'pageSize' => 10,
'fields' => 'files(id, name, mimeType)'
]);
return $files->getFiles();
}
function uploadToDrive(Request $request)
{
$uploadedFile = $request->file('file');
$client = $this->getClient($request->client_id);
$service = new \Google\Service\Drive($client);
$fileMetadata = new \Google\Service\Drive\DriveFile([
'name' => $uploadedFile->getClientOriginalName()
]);
$file = $service->files->create($fileMetadata, [
'data' => file_get_contents($uploadedFile->getRealPath()),
'mimeType' => $uploadedFile->getClientMimeType(),
'uploadType' => 'multipart',
'fields' => 'id, name'
]);
return $file;
}
function downloadDriveFile(Request $request)
{
$client = $this->getClient($request->client_id);
$service = new \Google\Service\Drive($client);
$file = $service->files->get($request->file_id, ['fields' => 'name, mimeType']);
$response = $service->files->get($request->file_id, ['alt' => 'media']);
return response()->streamDownload(function () use ($response) {
echo $response->getBody();
}, $file->getName(), [
'Content-Type' => $file->getMimeType()
]);
}
function getClient($clientId)
{
$integration = CloudIntegration::where('user_id', $clientId)
->where('provider', 'google_drive')->first();
if (!$integration) {
return $this->responseWithError(null, "Client not found", 404);
}
$token = json_decode($integration->access_token, true);
// $token = $integration->access_token;
$client = new Google_Client();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$client->setRedirectUri(config('services.google.redirect'));
$client->setAccessToken($token);
if ($client->isAccessTokenExpired()) {
$newToken = $client->fetchAccessTokenWithRefreshToken($integration->refresh_token);
$integration->update([
'access_token' => json_encode($newToken),
'access_token_expires_in' => now()->addSeconds($newToken['expires_in'])
]);
$client->setAccessToken($newToken);
}
return $client;
}