Create Storage Disks Dynamically in Laravel
Imagine you're developing a SaaS application where every customer has a separate file storage directory.
Instead of creating a separate disk configuration for every customer, Laravel allows you to build storage disks dynamically.
Basic Usage
use Illuminate\Support\Facades\Storage;
$disk = Storage::build([
'driver' => 'local',
'root' => storage_path('app/tenants/1'),
]);
$disk->put('document.pdf', $content);
Laravel creates a filesystem instance using the supplied configuration.
You don't need to define this disk in config/filesystems.php.
Use Dynamic Storage Paths
Imagine your application stores files separately for each tenant:
$tenantId = 25;
$disk = Storage::build([
'driver' => 'local',
'root' => storage_path("app/tenants/{$tenantId}"),
]);
$disk->put('invoices/invoice-1001.pdf', $content);
The file is stored inside that tenant's storage directory.
Use Amazon S3 Dynamically
You can also build an S3 disk using runtime configuration:
$disk = Storage::build([
'driver' => 's3',
'key' => config('services.aws.key'),
'secret' => config('services.aws.secret'),
'region' => 'ap-south-1',
'bucket' => 'customer-documents',
]);
$disk->put('reports/report.pdf', $content);
This allows you to use different storage configurations without defining every disk in advance.
When Should You Use It?
- Multi-tenant applications
- Customer-specific storage
- Dynamic cloud storage configurations
- Separate project directories
- Applications with configurable storage locations