Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

Unique File Names

I have all my user uploads in a database, but I need unique file names.

What would be considered the best practice here?

Use a random string? Although you could get duplicates. Perhaps catch the duplicates and try again with a new random string? Use a UUID/ULID as the file name and make this column unique in the database, but maintain original int primary keys for speed. Something else?

0 likes
14 replies
Snapey's avatar

best practice is to not store the upload data in the database if thats what you were thinking.

What I do is have columns of disk, original_name and filename

Create a file system disk corresponding to the folder where you want to store the media

write the file with the default 40 character random filename that Laravel generates.

Store the disk, the original name and the filename in the database.

The original name is used where I need to allow the user to download their file and get it back with the same name it had on upload.

The random filename is used in the html like;

<img src="{{ Storage::disk($media->disk)->url($media->filename) }}" />
panthro's avatar

@Snapey thanks, if I generate a random filename, what about name clashes, what to do?

panthro's avatar

@Snapey I write the file details to the database first, then write the file, I catch for errors and rollback. No need to delete the file upon error if it's the last thing written.

Snapey's avatar
Snapey
Best Answer
Level 122

@panthro do you realise how much entropy there is in 40 characters? I answered this recently, its 5*10^71

so 5 and 71 zeros after it.

you could import thousands of media per second with no care of a collision

1 like
martinbean's avatar

@panthro Do you think Laravel would use it if there was a high chance of duplicate filenames…?

You also don’t need it before uploading. When you upload it—using the example in docs I linked you to—the path will be returned, which you can then store in the database:

Post::create([
    'headline' => $request->input('headline'),
    'image_path' => $request->file('image')->store('images'),
]);
jlrdw's avatar

@josejoao if you do this use regex to only allow numbers, letters, dash, and underscore. Remove anything else.

And check extension to verify it is one of the allowed extensions.

Please or to participate in this conversation.