How to Upload Files On Google Cloud Storage in Laravel

Do you want to integrate Google Cloud Storage with your Laravel application? You may want to use Cloud Storage to upload your files and access them on your website. In this article, I’ll show you how to upload files on Google Cloud Storage from your Laravel application.

What’s Google Cloud Storage?

Google Cloud Storage is an online file storage service. It allows storing and accessing data on the Google Cloud Platform infrastructure.

This service stores objects which are organized into buckets. Here, an object means a document and can be anything like an image, zip, PDF, spreadsheet, etc.

Storing your important files in the cloud is always recommended. On the cloud, your documents will remain safe and up 99.99% of the time.

When it comes to integration, you’ll have to upload your files programmatically on Cloud Storage. Google Cloud Storage provides a RESTful service through which you can upload files on the Cloud. To establish a bridge between your application and the Cloud service you’ll require to create a service account. This account is used for authentication purposes.

Creating a Service Account

Below are the steps to create your service account on the Google Cloud. At the end of the steps, you will get the JSON file containing the credentials required for authentication.

Create a service account:

  • In the Cloud Console, go to the Create service account page.
  • Select/Create a project.
  • In the Service account name field, enter a name. The Cloud Console fills in the Service account ID field based on this name. To the Service account description field, provide a description.
  • Click Create.
  • Click the Select a role field. Under Quick access, choose Basic and then the Owner.
  • Click Continue.
  • Click Done to finish creating the service account.

Create a service account key:

  • In the Cloud Console, click the email address for the service account that you created.
  • Click Keys.
  • Click Add key and then Create a new key.
  • Click Create which will download a JSON key to your computer.
  • Click Close.

The next important step is – on your Google project enable the Cloud Storage API from the API library section.

Copy the JSON file into the root directory of your Laravel installation. It’s the same directory where your .env file is located. In Laravel, we set the document root to the public folder. So these sensitive files in the root location won’t be accessed on the internet. Even if someone tries to access them, Laravel will display a 404 page.

This JSON file should not be stored in your Git repository. Add this file to the .gitignore so it won’t be committed.

Create a Bucket on Google Cloud Storage

Google Cloud Storage keeps all documents inside the bucket. While creating a bucket on Google Cloud, you have to follow certain naming guidelines. The below points should be considered when you create a bucket.

  • Bucket names must contain only lowercase letters, numbers, dashes, underscores, and dots. Spaces are not allowed.
  • Bucket names must start and end with a number or letter.
  • Bucket names must contain 3-63 characters. Names containing dots can contain up to 222 characters, but each dot-separated component can be no longer than 63 characters.
  • Bucket names cannot be represented as an IP Address in dotted-decimal notation.
  • Bucket names cannot begin with the “goog” prefix.
  • Bucket names cannot contain “google” or close misspellings, such as “g00gle”.

Upon creating a bucket, add its name to the .env file of your Laravel application as follows.

GOOGLE_CLOUD_BUCKET="BUCKET_NAME"

Using the constant GOOGLE_CLOUD_BUCKET, we’ll fetch the bucket name later in the code.

Create a Controller, View, Routes

Now we require a user interface where you can browse the image and submit it. This image then sends to the server for further processing. For this, let’s start with creating a FileController using the command below.

php artisan make:controller FileController

Next, in your blade file say file.blade, add the following HTML.

@if (session('success'))
    <strong>{{ session('success') }}</strong>
@endif

<form action="{{ url('store') }}" method="post" enctype="multipart/form-data">
    @csrf
    <p><input type="file" name="myfile" /></p>
    <button type="submit" name="submit">Submit</button>
</form>

Define 2 routes in the routes/web.php. One is to call view and the other is to accept data posted from the client-side.

Route::get('upload', 'FileController@index');
Route::post('store', 'FileController@store');

Upload Files to Google Cloud Storage

To establish a bridge between your Laravel app and Google Cloud Storage, install the google/cloud-storage library in your Laravel application.

composer require google/cloud-storage -W

Create a symbolic link from public/storage to storage/app/public using the command:

php artisan storage:link

At this point, we are good to write the actual code. The main code will go obviously inside the controller. The FileController will perform the following operations:

  • Call the View.
  • initialize StorageClient by providing a JSON key file.
  • Store file on local disk i.e. in storage directory.
  • Send this stored file to the bucket created on Google Cloud Storage.
  • Remove the file from the local disk i.e. from the storage folder.

FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Google\Cloud\Storage\StorageClient;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    public function index()
    {
        return view('file');
    }

    public function store(Request $request)
    {
        if ($request->hasFile('myfile')) {
            try {
                $storage = new StorageClient([
                    'keyFilePath' => base_path(). '/JSON_KEY_FILENAME',
                ]);

                $bucketName = env('GOOGLE_CLOUD_BUCKET');
                $bucket = $storage->bucket($bucketName);

                //get filename with extension
                $filenamewithextension = $request->file('myfile')->getClientOriginalName();

                //get filename without extension
                $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);

                //get file extension
                $extension = $request->file('myfile')->getClientOriginalExtension();

                //filename to store
                $filenametostore = $filename.'_'.uniqid().'.'.$extension;

                Storage::put('public/uploads/'. $filenametostore, fopen($request->file('myfile'), 'r+'));

                $filepath = storage_path('app/public/uploads/'.$filenametostore);

                $object = $bucket->upload(
                    fopen($filepath, 'r'),
                    [
                        'predefinedAcl' => 'publicRead'
                    ]
                );

                // delete file from local disk
                Storage::delete('public/uploads/'. $filenametostore);

                return redirect('upload')->with('success', "File is uploaded successfully. File path is: https://storage.googleapis.com/$bucketName/$filenametostore");

            } catch(Exception $e) {
                echo $e->getMessage();
            }
        }
    }
}

Head over to the browser, run the upload route, choose a file, and submit the form. You should get a success message along with the link to your uploaded file on Google Cloud Storage.

In our code, I keep file access to the public by passing 'predefinedAcl' => 'publicRead'. It means everyone having a link can access the file. If you wish to keep the file private, remove the second parameter passed to the upload() method as shown below.

$object = $bucket->upload(
    fopen($filepath, 'r')
);

Delete File from Google Cloud Storage

You also want to delete documents from the Cloud Storage. It can be done by calling the delete() function on your bucket’s object of the document.

try {
    $storage = new StorageClient([
        'keyFilePath' => base_path(). '/JSON_KEY_FILENAME',
    ]);
 
    $bucket = $storage->bucket(env('GOOGLE_CLOUD_BUCKET'));
    $object = $bucket->object('FILE_NAME');
 
    $object->delete();
} catch(Exception $e) {
    echo $e->getMessage();
}

That’s it! It’s all about how to upload files on Google Cloud Storage in Laravel. In addition to file uploads, we also discussed deleting files from Cloud Storage. I hope this tutorial helps you quickly integrate Google Cloud Storage into your Laravel application. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *