Using Google Drive REST API with Laravel

In this tutorial, we’ll be using Google Drive REST API with Laravel application. We’ll authenticate the user with OAuth service and retrieve their access token. We’ll then use it to manage their drive data and perform read and write operations on their behalf. 

Create a new project and generate authentication scaffolding. Install Socialite and Google Client Library. We’ll use Socialite to authenticate the user with Google’s OAuth service.

Create Google Drive Application

Now head over to Google Developers Console and create or select an existing project. You can use this wizard to register Google Drive Application.

Now click continue and go to credentials.

Choose Google drive API, select Web Server and check User Data. 

Enter client ID name and enter Javascript origin and redirect URIs. Enter your domain name instead of localhost address for production. Redirect URI will be used to redirect users back to your app after authentication. Create client ID and enter product name. Download JSON credentials file and save it.

 

Now click on Enable API and Services from the dashboard.

Search for Google Drive and Google+ APIs and make sure both are enabled.

Configure Google Service

Now edit config/serivces.php  and add google service at the end of services array.

Now define enviroment variables in .env file.

You Redirect URI must match with the one we entered during application setup.

OAuth Authentication

Add these routes to your app/routes/web.php  file.

Now define both methods in LoginController.

We’re using “https://www.googleapis.com/auth/drive” scope to request user permissions for managing their drive data in redirectToGoogleProvider() method. In handleProviderGoogleCallback()  method, we’re creating a new user if it doesn’t exist. if it exists, we’re updating their refresh_token. Make sure you add this column to your user’s table by modifying user migration and setting the password to nullable.

Dependency Injection

Create GoogleServiceProvider. We’ll inject Google Client class into service container to avoid unnecessary instantiation.

After instantiation of Google_Client  class, we’re reading google service credentials and creating a temporary file with it. We’re doing this because setAuthConfig() method expects json file with credentials that we downloaded after setting up drive app. Now every time we type hint Google_Client in our methods, we’ll have access to this instance from service container.

Routes and Controller

Add these routes to your app. Create DriveController and implement these methods to handle requests.

In our controller’s constructor, we can’t access Auth user, this is why we’re using a closure based middleware. We’re setting refresh token and creating a new instance of  Google_Service_Drive  with Google_Client  instance from service container.

Retrieving Folders

In getDrive()  method, we’re calling ListFolders($id)  method with ‘root’ param. root refers to the main directory of google drive. Then we’re retrieving root folders with  files->listFiles($optParams) method. If you want to access files in a specific folder you can pass folder ID instead of root to access its files. You can also recursively calling ListFolder() method in foreach loop.

Creating Files from Storage and Form Uploads

createFile($file, $parent_id = null) takes two arguments. First one is a file. It can be a file object retrieved from requests or a storage path. You can pass parent id as the second param. If you want to create a new file under a specific folder. After creating file, it returns file id.

Creating Folders

You can pass folder name to  createFolder($folder_name) method to create a new folder and get its ID.

Deleting Folders

To delete a folder or file, all you have to do is to pass an id to deleteFileOrFolder($id) and it will be deleted from the drive.

I’ve set up an example project repository. If you’ve any issue integrating Google Drive API in your app, comment your issue and i’ll try to help you with it.

Share this post

3 thoughts on “Using Google Drive REST API with Laravel”

  1. Nice. Useful tutorial.
    Could you please make a tutorial on a Timesheet app. Users/Employees would enter their daily work: start time, end time, project name, notes and any expenses.
    Many Thanks !

  2. I have an error when i´m trying to upload a file, the app says “Trying to get property of non-object” What is the problem with the code?

    1. Are you uploading the file through a web form? Make sure you have enctype="multipart/form-data" on your form. Also make sure $request->file('file') exists before passing it to createFile($request->file('file')) method.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.