Laravel Project Setup for Google Drive API Integration (Part 2)

Arlind Musliu Portrait
Arlind Musliu

January 25, 2024 · 3 min read · 3,591 views

Laravel and Google Drive Blogpost Image

Laravel 11 Google Drive Storage package

After setting up the Google Drive API integration with Laravel 11, it's time to delve into the specifics of using the Laravel Google Drive Storage package. This second part of the guide will cover the installation process and demonstrate how to perform common file operations such as uploading, retrieving, and deleting files on Google Drive.

Support for Laravel 9 and PHP 8.1

It's important to note that this package is not only compatible with Laravel 11 but also supports Laravel 9 and PHP 8.1. This ensures that developers using the previous version of the framework or PHP can also take advantage of this integration.

Installation Steps

The README file in the repository provides additional instructions and guidance that will be helpful during the setup and usage of the package.

Install via Composer

Begin by running the following command in your project directory to install the package:

composer require yaza/laravel-google-drive-storage

Update Your .env File

Next, you need to update your .env file with the credentials obtained from the Google API. Add the lines below, making sure to replace 'xxx' with your actual details:

FILESYSTEM_CLOUD=google
GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com
GOOGLE_DRIVE_CLIENT_SECRET=xxx
GOOGLE_DRIVE_REFRESH_TOKEN=xxx
GOOGLE_DRIVE_FOLDER=

Configure filesystems.php

Modify your filesystems.php configuration file by adding the new disk settings for Google Drive:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DISK', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been set up for each driver as an example of the required values.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
            'throw' => false,
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
            'throw' => false,
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
            'throw' => false,
        ],

        'google' => [
            'driver' => 'google',
            'clientId' => env('GOOGLE_DRIVE_CLIENT_ID'),
            'clientSecret' => env('GOOGLE_DRIVE_CLIENT_SECRET'),
            'refreshToken' => env('GOOGLE_DRIVE_REFRESH_TOKEN'),
            'folder' => env('GOOGLE_DRIVE_FOLDER'),
        ]
    ],

    /*
    |--------------------------------------------------------------------------
    | Symbolic Links
    |--------------------------------------------------------------------------
    |
    | Here you may configure the symbolic links that will be created when the
    | `storage:link` Artisan command is executed. The array keys should be
    | the locations of the links and the values should be their targets.
    |
    */

    'links' => [
        public_path('storage') => storage_path('app/public'),
    ],

];

Using the Package

With the package installed and configured, you can now begin to interact with Google Drive through various file operations.

Uploading a File to Google Drive

You can upload a file to Google Drive by specifying the file's location and name:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class UploadFileController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
        Gdrive::put('your-folder/filename.jpg', $request->file('file'));

        return response('Image Uploaded!', 200);
    }
}

Retrieving a File from Google Drive

To get a file from Google Drive you can use:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class RetrieveFileController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
        $image = Gdrive::get('your-folder/filename.jpg');

        return response($image->file, 200)
            ->header('Content-Type', $image->ext);
    }
}

Streaming a Large File from Google Drive

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class StreamFileController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
		$readStream = Gdrive::readStream('your-folder/filename');
        
		return response()->stream(function () use ($readStream) {
					fpassthru($readStream->file);
				}, 200, [
					'Content-Type' => $readStream->ext,
				]);
    }
}

Downloading a File from Google Drive

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class DownloadFileController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
        $image = Gdrive::get('your-folder/filename.jpg');

        return response($image->file, 200)
            ->header('Content-Type', $image->ext)
			->header('Content-disposition', 'attachment; filename="'.$image->filename.'"');
    }
}

Deleting a File from Google Drive

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class DeleteFileController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
        Gdrive::delete('your-folder/filename.png');

   		return response('File Deleted!', 200);
    }
}

Deleting a Directory from Google Drive

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class DeleteDirectoryController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
        Gdrive::deleteDir('your-folder');

		return response('Directory Deleted!', 200);
    }
}

Creating a New Directory in Google Drive

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class CreateDirectoryController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
        Gdrive::makeDir('your-folder');

		return response('Directory Created!', 200);
    }
}

Listing All Folder & Files in Google Drive

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Yaza\LaravelGoogleDriveStorage\Gdrive;

class ListDirectoryController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): Response
    {
		$items = Gdrive::all('/');
		// or
        $items = Gdrive::all('your-folder');

        return response($items, 200);
    }
}

Conclusion

By following these steps and utilizing the package's features, you can efficiently manage files on Google Drive within your Laravel 11 application. The Laravel Google Drive storage package streamlines the process of interacting with the cloud, allowing you to focus on building and enhancing your application's core functionalities. Whether you need to upload user-generated content, serve files to your users, or manage documents in the cloud, this package provides a seamless way to integrate Google Drive into your Laravel application.


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 leading Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

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