0
votes

With the following code I save the file with a unique name. That's awesome, except I want it perfect. I rather see the image with a name like: path/to/file/name-of-the-file.jpg and if there's a new one with the same name I like it to be: path/to/file/name-of-the-file-2.jpg instead of a unique "hash" in front.

$path = $request->image->storeAs('themes', uniqid().'-'.$request->image->getClientOriginalName(), 'public');

Is there a way to extend / overwrite the class "UploadFile.php" and add an extra method to this? So I can add method like: storeAsUnique()

I can see it's called within /vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithInput.php on line 251 (in laravel 5.4).

I don't see how to extend this class.

1

1 Answers

0
votes

Definitely, hashed filenames are the way to go. I recommend you using them, because they eliminate much of the overhead of dealing with files that have alphanumeric-ish names. That being said, if you still want to take your approach mentioned above, there are a few things you could do.

You could extend UploadedFile and implement the storeAsUnique() method. Inside such method you could do:

1) Scan the directory with scandir() (or potentially glob() ) and allocate the results to a variable.

2) You will the compare each result to the name you want to give to the file you are about to create, say file.jpeg. If a match is found, then you will try to find file2.jpeg. If no match is found, you got it! Now suppose that in the second iteration, file2.jpeg is found. Then you will have to go on and try to find file3.jpeg.

The steps mentioned above, are fine for a small set of files. However, Imagine you have 100+ files that have a subsequent enumerated file, namely file1.jpeg to file100.jpeg then this operation will turn into a slow and resource expensive one, affecting the execution time of your script heavily. Of course that are many improvements that can be made to the 2-step recursive algorithm described above, but for many files, the outcome is generally the same.

I hope this points you in the right direction.

Cheers!