Quick Snippet Laravel – Dynamic Storage Disks – Saving files to a dynamic path
Use Case: You have defined your default disk inside config/filesystems.php
but this takes in a fixed value like
'local' => [ 'driver' => 'local', 'root' => public_path('client_uploads'), ],
What if the path is stored in a database table and you want to make use of that dynamic value to store your files.
Solution:
config( [ 'filesystems.disks.' . self::$disk => [ 'driver' => 'local', 'root' => getSetting('upload_dir'), ], ] );
Use the above snippet in your controller. Use a service provider if you want to use it everywhere. We are using the config
helper (that you use to retrieve a config value) for setting a value at runtime.
self::$disk
: is just a staic variable storing the name of the disk if the value was 'client_uploads'
then the key would become filesystems.disks.client_uploads
getSetting('upload_dir')
: is a custom method to fetch the value from a DB table which stores key-values.
Read about syntax of the config helper here