Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I switch between local and SFTP storage for media files in Laravel


How do I switch between local and SFTP storage for media files in Laravel


Here's how you can switch between local and SFTP storage for media files in Laravel:

Configure SFTP Disk

1. In your `config/filesystems.php` file, add a new disk configuration for SFTP:

php
'disks' => [
    // ...
    'sftp' => [
        'driver' => 'sftp',
        'host' => env('SFTP_HOST'),
        'username' => env('SFTP_USERNAME'),
        'password' => env('SFTP_PASSWORD'),
        'privateKey' => env('SFTP_PRIVATE_KEY'),
        'root' => env('SFTP_ROOT'),
        'timeout' => 10,
    ],
]

2. Make sure to add the necessary environment variables (`SFTP_HOST`, `SFTP_USERNAME`, `SFTP_PASSWORD`, `SFTP_PRIVATE_KEY`, `SFTP_ROOT`) to your `.env` file.

Use Different Disks for Media Collections

1. In your Eloquent model that has media, define the media collections and specify the disk to use for each collection:

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

    $this->addMediaCollection('documents')
         ->useDisk('sftp');
}

2. Now, when you add media to your model, it will be stored on the appropriate disk based on the media collection:

php
$model->addMedia($pathToImage)->toMediaCollection('images');
$model->addMedia($pathToDocument)->toMediaCollection('documents');

3. To retrieve media from the different disks, use the `getMedia` method:

php
$images = $model->getMedia('images');
$documents = $model->getMedia('documents');

Switch Disks Dynamically

If you need to switch the disk for a media collection at runtime, you can use the `setMediaDirectory` method:

php
// Store on SFTP disk
$model->setMediaDirectory('documents', 'sftp');
$model->addMedia($pathToDocument)->toMediaCollection('documents');

// Store on local disk
$model->setMediaDirectory('documents', 'local');
$model->addMedia($pathToDocument)->toMediaCollection('documents');

By following these steps, you can easily switch between local and SFTP storage for different media collections in your Laravel application. This allows you to have more control over where your media files are stored based on your application's requirements.

Remember to configure the SFTP disk correctly with the necessary environment variables and ensure that the SFTP connection is properly set up.

Citations:
[1] https://www.tutsplanet.com/laravel-download-files-to-storage-from-sftp/
[2] https://laravel.com/docs/11.x/filesystem
[3] https://en.ccc.tc/article/how-do-i-synchronize-files-with-laravel%27s-storage%27s-sftp-driver
[4] https://laracasts.com/discuss/channels/laravel/access-files-on-a-separate-server-via-sftp-in-laravel
[5] https://www.educative.io/answers/how-to-fix-storage-link-not-working-issue-in-laravel