How To Setup Laravel Backup On Google Drive?

Harish Kumar · · 7555 Views

In this article, I will show how to store automatic Laravel backup on Google Drive using spatie/laravel-backup package and Google Flysystem.

It is necessary to take the backup of the database and files consistently. It allows developers to ensure the second state of data in case of any accidental failures or something turns out badly with your server or application.

Installation of `laravel-backup` package

We'll start by installing spatie/laravel-backup package. For that, run the following command in your terminal.

composer require spatie/laravel-backup

Publish the config file:

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

It will publish the configuration file in config/backup.php. Now, configure your backup according to your need.

You can read more about backup configuration and scheduling for automatic backup in this post: How to Set up Automatic Laravel Backup for database and files?

Our next step is to add google in the disk option in the config/backup.php.

'disks' => [
    'google',                
    'local',             
],

Right now, we don't have a google disk available. So, our next step is to integrate Google Drive as a Laravel filesystem.

Setup Google Drive as Filesystem in Laravel

For that, we need to install a Flysystem adapter for Google drive. So, run the following command in your terminal:

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

Once it installed successfully, create a new service provider using the following command:

php artisan make:provider GoogleDriveServiceProvider

Then, inside the boot() method add the Google driver for the Laravel filesystem:

// app/Providers/GoogleDriveServiceProvider.php

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);
    });
}

Afterward, register your GoogleDriveServiceProvider provider inside the config/app.php file.

Now the Google drive is ready. At this point, we will add the storage disk configuration to config/filesystem.php:

return [
  
    // ...
    
    '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'),
        ],
        
        // ...
        
    ],
    
    // ...
];

Next, we need to update .env file. In this environment file we need to add the following Google credentials:

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

Get Google credentials

For the above-mentioned environment variables, It requires us to make an application in Google, this isn't so difficult. So, go to the google console: https://console.developers.google.com/

Start by creating a new project using the dropdown at the top.

How To Setup Laravel Backup On Google Drive?

After you enter a name, it takes a couple of seconds before the project is successfully created.

Make sure you have the project selected at the top.

At that point go to "Library" and search for "Google Drive API":

How To Setup Laravel Backup On Google Drive?

And then enable the Google Drive API.

How To Setup Laravel Backup On Google Drive?

Then, go to "Credentials" and click on the tab "OAuth Consent Screen". Here you will get options to select user type, select "External" option, and click the "CREATE" button.

How To Setup Laravel Backup On Google Drive?

Fill in "App Name", "User support email" and "Email" in the Developer contact information and click Save And Continue button. For other forms "Scopes", "Test Users" and "Summary" click on Save And Continue button and go to the dashboard. Don't worry about the other fields.

How To Setup Laravel Backup On Google Drive?

On the OAuth consent screen, you will see that the App's Publishing status is testing. Here we need to publish the App. So, click the Publish App button and confirm.

How To Setup Laravel Backup On Google Drive?

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

How To Setup Laravel Backup On Google Drive?

For "Application type" choose "Web Application" and give it a name.

Enter your “Authorized redirect URIs”, your production URL (https://mysite.com) — or create a separate production key later.

Also add https://developers.google.com/oauthplayground temporarily, because you will need to use that in the next step.

How To Setup Laravel Backup On Google Drive?

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

Getting your Refresh Token

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

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

How To Setup Laravel Backup On Google Drive?

In step 1 on the left, scroll to "Drive API v3", expand it, and check each of the scopes.

How To Setup Laravel Backup On Google Drive?

Click "Authorize APIs" and allow access to your account when prompted.

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

How To Setup Laravel Backup On Google Drive?

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

How To Setup Laravel Backup On Google Drive?

Get folder ID in Google Drive where to store backup

Here folder ID is optional. If you set folder ID to null, in that case, it is going to store backup files in the root path of Google Drive.

You can get the folder ID from the URL, as shown in the below image.

How To Setup Laravel Backup On Google Drive?

Now, we have Google Client ID, CLIENT SECRET, REFRESH TOKEN, and FOLDER ID. Update these values in the .env file.

Now, let's check to see if it works, run this command to see if it worked:

php artisan backup:run

Resolving possible error

If you encounter an error "File not found" you might want to set the name to an empty string inside the backup configuration file.

// config/backup.php

'name' => '',

That is it, you should now have automatic backups to your Google Drive using the laravel-backup package from Spatie, and the Flysystem driver from Google.

1

Please login or create new account to add your comment.

1 comment
AM SAMOL
AM SAMOL ·

Hello sir my name AM SAMOL i have problem with laravel backup to google drive with message below

Copying zip failed because: There is a connection error when trying to connect to disk named cloud-backup. Sending notification failed

Please help me

You may also like:

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

Part #1: Closure-based Custom Laravel Validation

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar

Mobile App Development Process

With businesses adopting a mobile-first approach and the growing number of mobile apps, successful mobile app development seems like a quest. But it’s the process that determines (...)
Narola Infotech

What are Laravel Macros and How to Extending Laravel’s Core Classes using Macros with example?

Laravel Macros are a great way of expanding Laravel's core macroable classes and add additional functionality needed for your application. In simple word, Laravel Macro is an (...)
Harish Kumar