Ensuring data backup is the most vital part of any application’s redundancy plan. It allows developers to ensure the second state of data in case of any accidental failures, so that the continuation of processes doesn’t get affected and the overall operation always stays in flow.
Therefore, backup is an integral part of any application development life cycle, as it provides a suitable layer of data persistence in the events of unwanted disasters. Depending on your applications, the preference of developing dedicated backups always stays with you. It can include files, database, caches or any other information.
Laravel, also emphasizes heavily on making redundant backups of web applications. It has introduced several backup packages to ensure the risk-free state of apps in case of accidental failures. The most known and popular among them is Spatie.
This Laravel 5 package creates application backup in a zip file containing all the directory files you specify along with a dump of your database. You can store that backup on any file system configured in your application.
In this article, I will demonstrate how to setup Google Drive backup of a Laravel application using Spatie’s backup package and Google Flysystem.
Prerequisites
This tutorial motive, I take that you have a Laravel application installed on a web server. My setup is:
- Laravel 5.5
- Google Drive API
- MySQL Database
I have decided to host my Laravel application on Cloudways hosting PHP website. It has great devstack for developers and offers highly secured platform. You can also signing up for an free account.
Backup Package Installation
For backing up your Laravel files and database, you need to install this package first into your application. Open the SSH terminal and initiate the installation by entering the following command:
composer require spatie/laravel-backup
Add Package into Service Provider
Once the installation is complete, the next step is to add the service provider of the package in the Config/app.php file. Open the app.php file and add the service provider inside the providers array.
‘providers’ => [
…
Spatie\Backup\BackupServiceProvider::class]
After adding this package, run the following command for compiling the above process.
php artisan vendor:publish –provider=”Spatie\Backup\BackupServiceProvider”
Flysystem adapter for Google Drive
Next step is the installation of Flysystem adapter for Google drive. Run the following command to start the process:
composer require nao-pon/flysystem-google-drive:~1.1
Create Service Provider
.
After successfully adding backup package, it’s time to create a new service provider naming as GoogleDriveServiceProvider by pasting the following command:
php artisan make:provider GoogleDriveServiceProvider
Next, paste the following code into boot() function under given service provider.
\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);
});
Afterwards, register your Google Drive iServiceProvider provider within the config/app.php file.
Backup Schedule:
Scheduling backup at regular intervals is a good practice for maintaining effective data redundancy. You must schedule your backup time by pasting following code in the kernel file.
// Backups (to Google Drive)
$schedule->command(‘backup:clean’)->dailyAt(’01:30′);
$schedule->command(‘backup:run –only-db’)->dailyAt(’01:35′);
Backup Disk
To use Google’s driver, open the app/backup.php file and change the ‘local’ driver within it to ‘google’.
‘disks’ => [
‘google’,
‘local’,
],
Setup Filesystems
Now to add the storage disk, paste the following code to your config/filesystems.php file.
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’),
],// …
],
// …
];
Getting Google Drive API
Getting the Google Drive API is not that hard as it looks. First, go the Google console and create a new project as shown below:
After successfully creating projects, go to library and select Google API for drive and click on enable to enabling this API.
After creating the project, go to the API library and select the Google Drive API. Within it click on the enable button for enabling the Google API. Once you enable the API, you will get Client ID and Client secret – the keys which you have to use in the config/filesystems.php file defined above.
Setup Credentials
In order to setup Credentials, go to the “Credentials” tab and navigate to the “OAuth Consent Screen” tab. Fill your desired “Application name” there and save it. Leave the remaining fields as they are not required at this stage.
Now go back to the Credentials, click on the button “Create Credentials” and select the “OAuth Client ID”.
To create Client ID, choose “Web Applications” and enter a name of your preference. Enter your website URL (https://abcsite.com) on the ““Authorized redirect URIs” section. You can create a separate production key in the later stage as well. While also add the ‘https://developers.google.com/oauthplayground’ address there as you will require it in the next step.
Go to the https://developers.google.com/oauthplayground, click on the settings icon located on the top right corner. Check the “Use your own OAuth credentials” box and paste your Client ID and Client Secret which you have acquired above.
In step 1, scroll down to “Drive API v3” and expand it to check all define scopes.
To allow access to your account, click on “Authorize APIs”. In step 2, click on the “Exchange authorization code for tokens” button and checkout the “Auto-refresh the token before it expires” box below Access token field.
Before proceeding to step 3, click on the step 2 again and you will see your refresh token there. Note that refresh token as it will be added in the .env file under “GOOGLE_DRIVE_REFRESH_TOKEN ” in the next step.
Setup .env File
Now you have got all the Google Drive credentials (Client ID, Secret key and Refresh token) required for setting up .env file. It’s time to open up the file and add them in the relevant fields:
GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com
GOOGLE_DRIVE_CLIENT_SECRET=xxx
GOOGLE_DRIVE_REFRESH_TOKEN=xxx
GOOGLE_DRIVE_FOLDER_ID=null
Store Backup in Google Drive Folder
Leave the Google Drive Folder ID as null, if you want to store files in the root directory of your Google Drive. Otherwise, create a folder within your Drive to store files separately.
You can name folders within your Google Drive with duplicate names. Because Google Drive identifies its folders with a unique folder ID, you can see those folder IDs in the URL whenever you open any folder.
As mentioned above, if you want to store files in a specific folder, add that folder ID under the GOOGLE_DRIVE_FOLDER_ID in the .env file. If left null, it will store all files to the root of the Google Drive.
Now it’s time to run the backup live. Enter the following command to initiate the backup process:
backup:run –only-db
Final Words
In this article, i have given a brief account on how to setup Google Drive backup of a Laravel application using Spatie and Google Flysystem. The article also explains why backups are an integral part of any application and what value it brings in case of unwanted failures. If you still have further questions in regards to this article, or want to contribute your thoughts on the topic, feel free to write down your comments below in the comment section.