I keep multiple FTP accounts in a database table and would like each one to be available as a storage disk in Laravel.
Normally, Laravel's disks are defined in config/filesystems.php
. But instead of hardcoding my FTP accounts there, I would like to define them on the fly (in a middleware).
Is this possible? How do I accomplish that?
Laravel's FilesystemManager has methods to create most common disks.
<?php
use Illuminate\Filesystem\FilesystemManager;
$fsMgr = new FilesystemManager(app());
// local disk
$localDisk = $fsMgr->createLocalDriver(['root' => "/path/to/root"]);
// FTP disk
$ftpDisk = $fsMgr->createFtpDriver([/* FTP options */]);
// SFTP disk
$sftpDisk = $fsMgr->createSftpDriver([/* SFTP options */]);
// S3 disk
$s3Disk = $fsMgr->createS3Driver([/* S3 options */]);
Apart from that, you can create any filesystem supported by your league/flysystem installation, you only need to wrap it in Illuminate\Filesystem\FilesystemAdapter:
<?php
use League\Flysystem\FilesystemInterface;
// create any Flysystem instance and wrap it in Laravel's adapter
$myDisk = new FilesystemAdapter(/* \League\Flysystem\FilesystemInterface */ $filesystem);
This way you create your disks on-the-fly, without the need to modify the application config, handy if you have lots of connections, for example, to partners' FTP/SFTP servers, GCloud or S3 buckets.
I created a service provider MyDiskServiceProdiver
with this method:
public function boot()
{
MyDisk::all()->each(function(MyDisk $myDisk) {
$this->app['config']["filesystems.disks.{$myDisk->name}"] = ['driver' => $myDisk->driver] + $myDisk->config;
});
}
Where the config
attribute is of type json in database and holds several driver-specific attributes.
Create a new service provider
php artisan make:provider FileSystemServiceProvider
Register the provider in the config/app.php
If you open the config/app.php
file included with Laravel, you will see a provider's array
. register the created service provider there.
In The Boot Method
of the created service provider use the below-mentioned code to register the disks
Assuming fileSystemsDetails
is the model name
public function boot() {
DomainSettings::all()->each(function(DomainSettings $myDisk) {
if (!is_null($myDisk->driver_name) && !is_null($myDisk->driver_type)
&& !is_null($myDisk->driver_host) && !is_null($myDisk->driver_username) && !is_null($myDisk->driver_password)) {
$this->app['config']["filesystems.disks.{$myDisk->driver_name}"] =
[ 'driver' => $myDisk->driver_type,
'host' => $myDisk->driver_host,
'username' => $myDisk->driver_username,
'password' => $myDisk->driver_password,
'root' => $myDisk->driver_root,
];
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With