JoukeBouke's avatar

What is the best way to store uploaded file paths/names?

I've been thinking about this for quite some time already. There are several ways (at least that I'm going to describe here) to store a file name in the database. For my examples I will use an example path "/storage/app/public/filename.png":

  1. /device/root/app/storage/public/filename.png
  2. /storage/public/filename.png
  3. /public/filename.png
  4. filename.png
  5. filename

After going over pro's and cons of all options there, I think that using just "filename.png" is the best all-round solution. Correct me if I'm wrong about any of this, but storing it like that is

  • Environment-agnostic
  • Still explicit (no mix-ups with extensions for example)
  • Very easy to change the destination of this file to where ever, all you have to do is update the according disk (assuming there is one)

However to make this as easy to change as possible you need to add a disk for that file path in the filesystem config. So number 3 is my close 2nd place in that regard, where you don't need a custom filesystem disk, but if you were to change the location of the file, you'd need a script to also update all database records. So essentially for me it comes down to is should I leave it up to the database or codebase to decide the path to the file? Or is there a better solution I haven't mentioned here?

(Assume a simple case where a user uploads an avatar and I might want to use different storage providers on different envs, without changing the db or code preferably)

0 likes
3 replies
jlrdw's avatar

Normally you would store file name with the extension.

laracoft's avatar
laracoft
Best Answer
Level 27

@joukebouke I normally prefer to go 1 step further by

  1. Storing the file as a unique UUID with no extension on the file system
  2. DB field uuid - file that is saved on the file system
  3. DB field name - Original uploaded name with extension
  4. Path should be decided in code and synced with file system, this will ensure good control without being affected by user data

The reasons are as follows:

  1. This allows any fancy filename without being constrained by the file system (i.e. NTFS is not fully compatible with EXT*)
  2. This allows for duplicate filenames without one overwriting the other
  3. This allows us to be flexible with the file paths without being limited by the path at time of saving

Hope it helps.

artcore's avatar

I have two columns for that, 'location' and 'filename'. The root is the public folder but could be set to something else

This way I can have nested folders inside the location field: say 'catalog/brand' or 'journal/articles/featured' where filename + extension is in the 2nd field.

I use a mutator to glue the columns to an href property on the model.

Please or to participate in this conversation.