Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Upload File to Google Drive Tutorial

Last Updated on July 4, 2024 by

Spatie Provider is a package that helps developers to upload files to Google Drive cloud servers using Laravel 11 applications with its file system.

Let’s start to setup a Laravel file system Storage driver with Google Drive API to upload file in cloud server:

Step 1 – Set Up Google Cloud Account

Click on https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts url, and create a google cloud account.

And in your newly created cloud service account click on Keys tab, click on Add Key button and select JSON option.

Step 2 – Set Up Bucket in Cloud

Now, click on https://console.cloud.google.com/storage/browser url, and create a new Bucket.

Note:- You can also add storage and permission in it.

Step 3 – Install Spatie Package

To use Google Cloud Storage APIs, run the following command to install spatie package:

composer require spatie/laravel-google-cloud-storage

Step 4 – Configure FileSystem

Edit config/filesystems.php file, and set up file system related information in it:

//config/filesystems.php

  'gcs' => [
            'driver' => 'gcs',
            'key_file_path' => env('GOOGLE_CLOUD_KEY_FILE', base_path('service-account.json')), // optional: /path/to/service-account.json
            'key_file' => [], // optional: Array of data that substitutes the .json file (see below)
            'project_id' => env('GOOGLE_CLOUD_PROJECT_ID', 'your-project-id'), // optional: is included in key file
            'bucket' => env('GOOGLE_CLOUD_STORAGE_BUCKET', 'your-bucket'),
            'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', ''), // optional: /default/path/to/apply/in/bucket
            'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', null), // see: Public URLs below
            'apiEndpoint' => env('GOOGLE_CLOUD_STORAGE_API_ENDPOINT', null), // set storageClient apiEndpoint
            'visibility' => 'public', // optional: public|private
            'visibility_handler' => null, // optional: set to \League\Flysystem\GoogleCloudStorage\UniformBucketLevelAccessVisibility::class to enable uniform bucket level access
            'metadata' => ['cacheControl'=> 'public,max-age=86400'], // optional: default metadata
        ],
          

Now, copy the service account JSON file, downloaded earlier to Laravel application base path.

Step 4 – Update .env File

Edit .env file, and add bucket nameproject id and filesystem driver in it:

GOOGLE_CLOUD_PROJECT_ID = 
GOOGLE_CLOUD_STORAGE_BUCKET=
FILESYSTEM_DRIVER = gcs

Step 5 – Upload File in Cloud

Run the following command to create a controller file and method in it to upload and retrieve the file from the google cloud server:

php artisan make:controller FilesController

Edit app/http/controllers/filesController.php file, and implement method in it to upload Files to Google Cloud Storage:

use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;

public function uploadFile(UploadedFile $file, $folder = null, $filename = null)
    {
        $name = !is_null($filename) ? $filename : Str::random(25);

        return $file->storeAs(
            $folder,
            $name . "." . $file->getClientOriginalExtension(),
            'gcs'
        );
    }
    
public function store(Request $request)
    {
        $link = $request->hasFile('file') ? $this->uploadFile($request->file('file'), 'Categories') : null;
        $category = new Categories();
        $category->name = $request->input('name');
        $category->file= $link;
        $category->save();

        return redirect()->back();
    }

Step 6 – Get and Delete Files from Cloud

You can get and delete files using the Storage Facade from cloud server:

//for get file from server
use Illuminate\Support\Facades\Storage;

Storage::disk('gcs')->url(path/to/file)

The above code will return the url like the following:

http://storage.googleapis.com/bucket-name/folder/your_file.png 

To delete a file from cloud server, you can use the following function:

http://storage.googleapis.com/bucket-name/folder/your_file.png 

Leave a Comment