Google Drive integration with Laravel

June 10, 2021 · 4 min read · 28,697 views

Laravel and Google Drive Blogpost Image

2024 UPDATE

To address the limitations and challenges presented in this article, we have published two subsequent articles: Google Drive API Setup for Laravel 10 Integration (Part 1) and Laravel Project Setup for Google Drive API Integration (Part 2). These articles offer comprehensive guides to setting up the Google Drive API with the latest Laravel version and utilizing the Laravel Google Drive Storage package for efficient file operations. We highly recommend reading these follow-ups to benefit from the most current practices and to resolve any issues encountered with the methods described herein.

Why Google Drive Integration?

In the ever-evolving world of web development, integrating different platforms can often pose a challenge. One such integration that we recently tackled was between Laravel and Google Drive. This article will guide you through the process, focusing on how to create a new file in Laravel and retrieve its ID from Google Drive.

Google Drive recognizes files through their unique IDs rather than their names. This can make it tricky to retrieve the ID of a file created in Laravel. However, with the right approach, this hurdle can be overcome.

Setting Up the Connection with Google Drive API

Before diving into the code, it's crucial to establish a connection with the Google Drive API. This can be done by following the steps outlined in this guide. The guide provides a simple walkthrough on how to create a new file in your connected Google Drive folder. If that's all you need, you can stop reading here.

However, if you need to upload files, get their ID, delete or change their names, continue reading. We'll assume you've completed the setup and managed to create a simple file on your Google Drive, as shown in the guide.

Coding with Laravel

For this project, we used Laravel Facades to refactor our code. However, to keep this article straightforward, we won't delve into that now. All the coding will be done inside a controller. So, create a controller and start coding.

Assume you're sending a request from your view, and we're accepting that request on our store function. The following code is needed to establish the connection with Google Drive:

$client = new \Google_Client();
$client->setClientId(env('GOOGLE_DRIVE_CLIENT_ID'));
$client->setClientSecret(env('GOOGLE_DRIVE_CLIENT_SECRET'));
$client->refreshToken(env('GOOGLE_DRIVE_REFRESH_TOKEN'));
$service = new \Google_Service_Drive($client);

Creating Client-Specific Folders

In our project, we needed to create a unique folder for each client. We also wanted a main folder separate from the root Google Drive folder. That's why we use parents, which takes the value of the folder from the env file. We save the folderID of this client so we can later navigate there or delete it if needed.

$fileMetadata = new \Google_Service_Drive_DriveFile([
	'name' => 'your folder name',
	'parents' => [env('GOOGLE_DRIVE_FOLDER_ID')],
	'mimeType' => 'application/vnd.google-apps.folder'
]);

$folderId = $service->files->create($fileMetadata, [
	'fields' => 'id'
]);

This is how the folder structure will look after implementing the code:

GoogleDriveRootFolder/ourMainFolder/ourNewClientFolder/ourfile.jpg

Uploading Files to Client Folders

After creating the client folder, we can upload our files there. We can use a simple HTML form to upload the file and in our case, the input name is myfile. We can skip the first line of code if we plan to rename the file, but we should include it if we want to use the original file name. We have a special folder for each client, and that's why we include them folderId in the parents section.

$fileName = $request->file('myfile')->getClientOriginalName();

$fileMetadata = new \Google_Service_Drive_DriveFile([
	'name' => $fileName,
	'parents' => [$folderId]
]);

$file = file_get_contents($request->file('myfile'));

$fileId= $service->files->create($fileMetadata, [
	'data' => $file,
	'mimeType' => 'image/jpeg',
	'uploadType' => 'multipart',
	'fields' => 'id'
]);

Deleting Files from Google Drive

Our file is successfully uploaded to the folder that we created a step before. Now, if we want to delete that file, we can make use of the Laravel Storage facade, taking into consideration that you did what was suggested in the article.

Storage::disk('google')->delete($item->items['fileId']);

That's it..!

A Note on Refresh Tokens

The refresh token provided by Google will be removed after 1 week. You must publish your app if you want to use it without the need to generate a new refresh token each week.

Conclusion

Linking Laravel to Google Drive can seem complex, but it gets much easier with a good plan. We hope this guide has made your journey smoother. Check our blog posts for more tips and real-world examples of web development.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!