How to use Google Cloud Storage to save the document directly into the bucket instead of saving it locally and pushing it to the GCS using phpdocx?
I currently have this code below where I am saving it locally, but I want to directly save it in GCS instead.
$newDocx->searchAndReplace($docxFromPath, public_path() . '/storage/agreements/docx' . $fileName, 'Company Name', 'Apple', $options);
P.S. I am using laravel 10
First you should install GCS on Laravel using the following composer command:
Then you should create Google Cloud Storage Credentials by creating a service account in your Google Cloud project and downloading the JSON key file. Try to store this file securely in your Laravel application and preferably outside the public folder.
After that you should configure the Laravel filesystem using a code like below by editing config/filesystems.php
Make sure to set the relevant environment variables in your
.envfile.Finally, you can use it like below in your code:
In this approach, the document is first saved to a local temporary file in your machine and then the contents of this file are read and uploaded to Google Cloud Storage.Finally, the local file is deleted.
Edit: After your last comment, I'm providing the following code:
First try installing the following package:
In your service provider or bootstrap file, add the following code to register the stream wrapper::
Instead of using a local path, use a GCS stream path. This requires understanding how stream wrappers work. For Google Cloud Storage, the path usually looks like
Modify your phpdocx creation and saving process like so:
This way, you will skip saving to the local server.