0

I wanted to know how do I avoid file collision in Laravel. Lets say I have two users with the same filename and both gets affected because one of them changed the file how do I go about avoiding that. Here is my code

 $file = $request->file('file');
      $myfilename = $vid->getClientOriginalName().uniqid();
      $mypath = $file->storeAs(
'video',
$myfilename);
      $location = public_path('/allvids',$myfilename);
      $file->move($location);
      $file->profile = $myfilename;

1 Answers1

0

As a general rule, you should be saving files with generated filenames. There's nothing wrong with storing the actual filename in the database, and then serving it as that, but in general, you should generate one. There's a few ways to do so.

time() use a unix timestamp

uniqid() generate a unique ID

Personally, I'd suggest the second.

Also, you're doing;

$file->store('video', $myFilename)

What you want is;

$file->storeAs('video', $myFilename)

The store() method will use the original filename of the file.

ollieread
  • 6,018
  • 1
  • 20
  • 36
  • I tried uniqid so many times it doesn't work it still changes the other person file. I am going to update my question and showed you what I did. –  Mar 11 '18 at 19:19
  • Updated my answer, take a look – ollieread Mar 11 '18 at 19:23
  • I tried the storeAS many times too. Still nothing has changed. –  Mar 11 '18 at 19:30
  • Then I don't know what the problem is. If you're using `uniqid()` and `storeAs()` there shouldn't be an issue. – ollieread Mar 11 '18 at 19:33
  • I don't know either. I just updated my code. Am I like doing something wrong cause this crazy. –  Mar 11 '18 at 19:50