Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I configure Laravel Media Library to work with Google Cloud Storage


How do I configure Laravel Media Library to work with Google Cloud Storage


Here are the steps to configure Laravel Media Library to work with Google Cloud Storage:

1. Install the required packages:


composer require spatie/laravel-medialibrary
composer require spatie/laravel-google-cloud-storage

2. Configure the Google Cloud Storage disk in your `config/filesystems.php` file:

php
'disks' => [
    // ...
    'gcs' => [
        'driver' => 'gcs',
        'key_file_path' => env('GOOGLE_CLOUD_KEY_FILE', base_path('service-account.json')),
        'project_id' => env('GOOGLE_CLOUD_PROJECT_ID', 'your-project-id'),
        'bucket' => env('GOOGLE_CLOUD_STORAGE_BUCKET', 'your-bucket'),
        'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', ''),
        'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', null),
        'apiEndpoint' => env('GOOGLE_CLOUD_STORAGE_API_ENDPOINT', null),
        'visibility' => 'public',
        'visibility_handler' => null,
        'metadata' => ['cacheControl' => 'public,max-age=86400'],
    ],
    // ...
]

3. Add the necessary environment variables to your `.env` file:


GOOGLE_CLOUD_KEY_FILE=service-account.json
GOOGLE_CLOUD_PROJECT_ID=your-project-id
GOOGLE_CLOUD_STORAGE_BUCKET=your-bucket

4. Use the Google Cloud Storage disk in your Eloquent model:

php
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class YourModel extends Model
{
    use InteractsWithMedia;

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('images')
             ->useDisk('gcs');
    }
}

5. Add media to your model using the Google Cloud Storage disk:

php
$yourModel = YourModel::find(1);
$yourModel->addMedia($pathToFile)->toMediaCollection('images');

6. Retrieve media from the Google Cloud Storage disk:

php
$images = $yourModel->getMedia('images');
foreach ($images as $image) {
    echo $image->getUrl();
}

Make sure to replace the placeholders in the configuration with your actual Google Cloud project details and environment variable values.

By following these steps, you should be able to configure the Laravel Media Library package to work with Google Cloud Storage for storing and retrieving media files in your Laravel application.

Citations:
[1] https://github.com/spatie/laravel-google-cloud-storage
[2] https://www.luckymedia.dev/blog/google-drive-api-setup-for-laravel-10-integration-part-1
[3] https://www.twilio.com/en-us/blog/file-upload-with-laravel-and-google-cloud-storage
[4] https://www.iankumu.com/blog/laravel-google-cloud-storage/
[5] https://stackoverflow.com/questions/75392195/spatie-laravel-medialibrary-google-cloud-storage-compatibility