Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I store media files on different filesystems with Laravel Media Library
    Laravel Media Library Filesystems Storage Eloquent Models s3 local disk media collections


How can I store media files on different filesystems with Laravel Media Library


Here's how you can store media files on different filesystems with the Laravel Media Library package:

1. Configure Filesystem Disks:
- In your `config/filesystems.php` file, configure the different filesystem disks you want to use, such as local, s3, etc.
- For example, you can add an `s3` disk for storing product images and a `local` disk for storing user avatars.

2. Specify Disk in Media Collections:
- In your Eloquent model, define the media collections and specify the disk to use for each collection.
- For example, in your `Product` model:

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

         $this->addMediaCollection('thumbnails')
              ->useDisk('local');
     }
     

- And in your `User` model:

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

3. Add Media to Different Collections:
- When adding media to your models, use the appropriate media collection name to store the files on the desired disk.
- For example, when adding a product image:

php
     $product->addMedia($request->file('image'))
             ->toMediaCollection('product_images');
     

- And when adding a user avatar:

php
     $user->addMedia($request->file('avatar'))
          ->toMediaCollection('avatars');
     

4. Retrieve Media from Different Collections:
- When retrieving media, you can access the files from the appropriate media collection.
- For example, to get the product images:

php
     $product->getMedia('product_images');
     

- And to get the user avatar:

php
     $user->getMedia('avatars');
     

By following these steps, you can store media files on different filesystems based on the model and media collection. This allows you to have more control over where your files are stored, which can be useful for organizing and managing your application's media assets.

Remember to configure the filesystem disks in your `config/filesystems.php` file and ensure that the necessary permissions and credentials are set up for each disk.

Citations:
[1] https://laravel.com/docs/11.x/filesystem
[2] https://www.youtube.com/watch?v=kUXKhjKvmsY
[3] https://naxon.dev/blog/laravel-media-library-load-only-1st-picture-efficiently
[4] https://stackoverflow.com/questions/78330207/how-to-save-files-in-a-specific-folder-with-laravel-media-library
[5] https://laracasts.com/discuss/channels/laravel/spatie-medialibrary-default-storage-depending-on-the-model?reply=918132