How to Upload Files On Google Cloud Storage in Laravel

Laravel comes with a powerful file system that allows you to manage your file storage easily. By default, Laravel provides support for AWS S3 that is integrated into its core. You’ll find the configuration is already set for S3 inside the config/filesystems.php file.

But, when it comes to using a cloud service other than S3 you have to build either your custom filesystem or search for the packages to fulfill your goal. Building a custom filesystem is quite complex and not everyone will be able to do it. On the other hand, you can use the packages available but it happens most of the time that the package is no longer maintained by the developer. It may cause issues in the future. I am not saying don’t use the packages but you should choose packages wisely. The maintainer of the package should have a reputation. Don’t pick the library blindly.

In this article, I show you how to integrate Google Cloud Storage in Laravel. I’m not gonna build a custom filesystem. Instead, I’ll use the google/cloud-storage library. As Google maintains this library we can trust this package. Following this tutorial, you’ll be able to upload files to Google Cloud Storage in Laravel.

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, spreadsheets, etc.

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

When it comes to applications, you’ll have to upload your files programmatically. Google Cloud Storage provides a RESTful service using which you can store the files through a program. To establish a bridge between your application and the Cloud service you’ll require to create a service account for authentication.

Creating a Service Account

Below are the steps to create your service account on the Google Cloud. At 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. A JSON key file will download 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 the 404 page.

This JSON file should also 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

While creating a bucket on the 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”.

Once you create 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 in the later part of a code.

Create a Controller, View, Routes

The target of this tutorial is uploading files on Google Cloud Storage. It requires you to create the HTML, access the web page containing your HTML, and submit a file on the server-side. Let’s start with creating a FileController using the command below.

php artisan make:controller FileController

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 – to access the page and 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 send your files on Google Cloud Storage, install the google/cloud-storage library to the Laravel application.

composer require google/cloud-storage

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

php artisan storage:link

After this, your FileController will perform the following steps:

  • 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.

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, we keep file access to the public by passing ‘predefinedAcl’ => ‘publicRead’. That means everyone has 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

In case of deleting a file from Cloud Storage, the following code will be used.

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

Conclusion

We have studied how to upload files on Google Cloud Storage in Laravel. We also discussed deleting files from Cloud Storage. I hope this tutorial helps you quickly integrate Google Cloud Storage into your Laravel application.

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.