Search code examples
randomfilenamesuuidlaravel-9

Generate unique file names in Laravel


In Laravel when using the storage Facade to save file uploads it uses Str::random(40) under the hood to auto generate unique filenames. Source https://github.com/laravel/ideas/issues/161

I have a requirement for a file upload site to ensue uploaded files have unique filenames.

So my question is Str::random(40) adequate in terms of collision proof or should I be using Str::uuid instead to generate unique filenames?


Solution

  • Str::random(40) will be a 40 character alpha-numerical string:

    Str::random(40);
    
    // '8Z5x6RG4RQmULcqDLkcUtjyL68qvHckGLXAJH9tv'
    
    Str::random(40);
    
    // 'StLruWT1d7t9DXoN0ixvQ6AqRltvJRWar0M9dl7A'
    
    // ...
    

    You can see this generates strings using numbers, uppercase letters, lowercase letters, and allowing repeating characters.

    If you use this answer and adjust the math to remove the 33 special characters (since Str::random() doesn't use things like @, !, #, etc.), you still end up with 62 unique options:

    • 26 uppercase
    • 26 lowercase letters
    • 10 numbers

    At a length of 40, this equates to 62^40, or 4.9e71, which is an astronomically large number, and one that you're not likely to get a duplicate from.

    So in short, yes Str::random(40) is more than adequate.

    If you feel anxious still, you can code in a simple check:

    public function generateFilename() {
      $filename = Str::random(40);
      if (Storage::disk('example')->exists($filename)) {
        $filename = generateFilename();
      }
    
      return $filename;
    }
    

    (Or similar; adjust to fit your needs as required)