Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use Amazon S3 as a disk for storing media files in Laravel Media Library
    Laravel Media Library Amazon S3 S3 disk setup Laravel Media Library configuration store media files on S3


Can I use Amazon S3 as a disk for storing media files in Laravel Media Library


Yes, you can use Amazon S3 as a disk for storing media files in Laravel Media Library. Here's how you can set it up:

1. Configure the S3 disk in your `config/filesystems.php` file:

php
'disks' => [
    // ...
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
    ],
    // ...
]

2. Set the `MEDIA_DISK` environment variable in your `.env` file to use the S3 disk:


MEDIA_DISK=s3

3. In your model, specify the disk to use for media collections:

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

4. Add media to your model using the `toMediaCollection` method and specify the disk:

php
$yourModel->addMedia($pathToFile)
          ->toMediaCollection('images', 's3');

5. Retrieve media from your model using the `getMedia` method:

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

By following these steps, you can store your media files on Amazon S3 using the Laravel Media Library package. Make sure to replace the placeholders in the S3 disk configuration with your actual AWS credentials and bucket information.

Note that you may need to install additional packages like `league/flysystem-aws-s3-v3` to use the S3 driver. Also, ensure that your AWS credentials have the necessary permissions to access and write to the specified S3 bucket.

Citations:
[1] https://stackoverflow.com/questions/70976347/problem-storing-laravel-medialibrary-pro-media-to-aws-s3
[2] https://github.com/spatie/laravel-medialibrary/discussions/3151
[3] https://laracasts.com/discuss/channels/code-review/spatie-media-library-upload-to-amazon-s3-bucket-subfolder
[4] https://naxon.dev/blog/laravel-media-library-load-only-1st-picture-efficiently
[5] https://spatie.be/docs/laravel-medialibrary/v11/basic-usage/retrieving-media