panthro's avatar

Storing a path for file uploads in config?

I want to store all my file uploads in a folder called uploads. Where would be the best place to store this string value?

I've considered the filesystem config, but if I do this:

'root' => storage_path('app/public/uploads'),`

Then I wont be able to use that disk to access other files that are not in uploads.

What is recommended here?

0 likes
4 replies
click's avatar

You can create a new "disk" for uploads. If you want to switch your uploads to a remote storage or to any other directory at later moment you can easily do so by changing the root (and move all of your uploads of course).

For example you can add an uploads disk to config/filesystems.php

'disks' => [
        'uploads' => [
            'driver' => 'local',
            'root' => storage_path('app/public/uploads'),
        ],
/** other disks */
]

Where you are working with the uploads

Storage::disk('uploads')->get('image.png');
// will retrieve the file located in storage/app/public/uploads/image.png
panthro's avatar

@click this doesn't seem right, I would want to change the disk via the env , so for development I would use the local disk, the when in production I would switch to s3 disk.

The way you mention would mean an extra layer of complications.

click's avatar

@panthro That is something you did not mention in your question. But the logic is the same. It is up to you how you want to maintain it. You could create multiple disk configurations or you can create a single one.

Depending on your requirements you can create an environment key UPLOADS_DRIVER and UPLOADS_PATH and change it on your production server.

 'uploads' => [
            'driver' => env('UPLOADS_DRIVER', 'local'),
            'root' => env('UPLOADS_PATH', storage_path('app/public/uploads')),
            /* add your s3 configs here: env('UPLOADS_S3_BUCEKT', ''), etc. 
        ],

See https://github.com/laravel/laravel/blob/10.x/config/filesystems.php for a sample of an S3 bucket and which config variables you must and can set. More information about laravels filesystem can be found at https://laravel.com/docs/10.x/filesystem

lyleyboy's avatar

Firstly you should ideally store these items in the ENV file, then use a Config to collect them. The config has a default value. This way you could have a service or something that makes the decision about which folder to use.

Hope that helps.

Please or to participate in this conversation.