Skip to content

Instantly share code, notes, and snippets.

@mehranhadidi
Forked from ivanvermeyen/!NOTE.md
Created August 15, 2017 08:52
  • Star 25 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mehranhadidi/38e38b80e3d533650ed2b94a0f95f7f1 to your computer and use it in GitHub Desktop.
Setup a Laravel Storage driver with Google Drive API

Setup a Laravel Storage driver with Google Drive API

Log in to your Google Account and go to this website:

https://console.developers.google.com/

Getting your Client ID and Client Secret

Create a new project using the dropdown at the top.

Create a new project

After you enter a name, it takes a few seconds before the project is successfully created on the server.

Make sure you have the project selected at the top.

Then go to Library and click on "Drive API" under "G Suite APIs".

Add Drive API

And then Enable it.

Enable Google Drive API

Then, go to "Credentials" and click on the tab "OAuth Consent Screen". Fill in a "Product name shown to users" and Save it. Don't worry about the other fields.

Consent Screen

Then go back to Credentials, click the button that says "Create Credentials" and select "OAuth Client ID".

Create Credentials

Choose "Web Application" and give it a name.

Add https://developers.google.com/oauthplayground in "Authorized redirect URIs". You will need to use this in the next step to get your refresh token. Once you have the token, you can remove the URI.

Credentials

Click Create and take note of your Client ID and Client Secret.

Getting your Refresh Token

Now head to https://developers.google.com/oauthplayground.

Make sure you added this URL to your Authorized redirect URIs in the previous step.

In the top right corner, click the settings icon, check "Use your own OAuth credentials" and paste your Client ID and Client Secret.

Use your own OAuth credentials

In step 1 on the left, scroll to "Drive API v3", expand it and check the first drive scope.

Check Scopes

Click "Authorize APIs" and allow access to your account when prompted. There will be a few warning prompts, just proceed.

When you get to step 2, check "Auto-refresh the token before it expires" and click "Exchange authorization code for tokens".

Exchange authorization code for tokens

When you get to step 3, click on step 2 again and you should see your refresh token.

Refresh Token

Getting your Folder ID

If you want to store files in your Google Drive root directory, then the folder ID can be null. Else go into your Drive and create a folder.

Because Google Drive allows for duplicate names, it identifies each file and folder with a unique ID. If you open your folder, you will see the Folder ID in the URL.

Folder ID

Install in Laravel

Pull in Flysystem Adapter for Google Drive:

composer require nao-pon/flysystem-google-drive:~1.1

Add the storage disk configuration to config/filesystem.php:

return [
  
    // ...
  
    'cloud' => 'google', // Optional: set Google Drive as default cloud storage
    
    'disks' => [
        
        // ...
        
        'google' => [
            'driver' => 'google',
            'clientId' => env('GOOGLE_DRIVE_CLIENT_ID'),
            'clientSecret' => env('GOOGLE_DRIVE_CLIENT_SECRET'),
            'refreshToken' => env('GOOGLE_DRIVE_REFRESH_TOKEN'),
            'folderId' => env('GOOGLE_DRIVE_FOLDER_ID'),
        ],
        
        // ...
        
    ],
    
    // ...
];

And update your .env file:

GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com
GOOGLE_DRIVE_CLIENT_SECRET=xxx
GOOGLE_DRIVE_REFRESH_TOKEN=xxx
GOOGLE_DRIVE_FOLDER_ID=null

Save GoogleDriveServiceProvider.php to app/Providers and add it to the providers array in config/app.php:

App\Providers\GoogleDriveServiceProvider::class,

Test Drive

Now you should be up and running:

Route::get('test', function() {
    Storage::disk('google')->put('test.txt', 'Hello World');
});
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class GoogleDriveServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
\Storage::extend('google', function($app, $config) {
$client = new \Google_Client();
$client->setClientId($config['clientId']);
$client->setClientSecret($config['clientSecret']);
$client->refreshToken($config['refreshToken']);
$service = new \Google_Service_Drive($client);
$adapter = new \Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter($service, $config['folderId']);
return new \League\Flysystem\Filesystem($adapter);
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
@mark-kccs
Copy link

mark-kccs commented Jan 6, 2021

Is there a way to get the folder ID after creating a new folder with Storage::disk('google')->makeDirectory($request->client, 0777, true);

@imokweb
Copy link

imokweb commented Jul 6, 2021

@tobihans
Copy link

tobihans commented Aug 3, 2021

Thanks!!!

@nordeveloper
Copy link

nordeveloper commented Dec 7, 2021

Storage::disk('google')->makeDirectory('test'), How can get created directory id ? or has ather method

return is bool, is not array, but google $this->getAdapter()->createDir($dirname, $config) return array folder id and etc

\vendor\league\flysystem\src\Filesystem.php

namespace League\Flysystem;

public function createDir($dirname, array $config = [])
{
$dirname = Util::normalizePath($dirname);
$config = $this->prepareConfig($config);

    return (bool) $this->getAdapter()->createDir($dirname, $config);
}

@ElevenMou
Copy link

Class "Google_Client" not found !!

@mocheaz
Copy link

mocheaz commented Jul 23, 2023

@ElevenMou i got it too. Did you find a solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment