Integrate Laravel with Google Cloud Storage for file upload, listing, downloading, and deleting
To integrate Laravel with Google Cloud Storage for file upload, listing, downloading, and deleting, you can follow these steps:
1. Install Required Packages
First, install the Google Cloud Storage package for Laravel. You can use google/cloud-storage
and laravel/filesystem
to handle cloud storage integration.
Run the following command in your Laravel project:
Then, install the league/flysystem-google-cloud-storage
package, which provides an adapter for Laravel’s filesystem:
2. Configure Google Cloud Storage
Next, configure your Google Cloud Storage credentials.
- Create a Google Cloud Storage Bucket if you don’t have one already.
- Generate a Service Account Key from Google Cloud Console:
- Go to the Google Cloud Console.
- Navigate to
IAM & Admin > Service Accounts
. - Create a new service account and assign it the
Storage Object Admin
role. - Download the generated JSON key file.
- Store the credentials in your Laravel project:
- Put the JSON key file in a secure directory (e.g.,
storage/app/google
).
- Put the JSON key file in a secure directory (e.g.,
3. Configure Filesystem in Laravel
Open config/filesystems.php
and add a new disk for Google Cloud Storage under the disks
array:
In your .env
file, add the following configuration:
4. Using Google Cloud Storage in Your Laravel Application
You can now use the Storage
facade to interact with Google Cloud Storage.
Uploading a File
Listing Files
You can list all files in a specific directory:
Downloading a File
You can download a file from Google Cloud Storage:
Deleting a File
To delete a file from Google Cloud Storage:
5. Testing Your Integration
Once everything is set up, test the functionality by uploading, listing, downloading, and deleting files using Laravel's storage facade.