Reputation: 3
I use this code to upload multiple files together in Laravel. However, all name files get duplicated. Please guide me.
if (is_array($files) || is_object($files)) {
foreach ($files as $file) {
$name = time().'.'.$file->getClientOriginalExtension();
$file->move(public_path('uploadmusic'), $name);
PostPhoto::create([
'post_id' => $post->id,
'filename' => $name
]);
}
}
1568314601.png
1568314601.png
1568314601.png
Upvotes: 0
Views: 713
Reputation: 35370
The precision of time()
is only a second - not enough time to make time()
report a different value when assigning $name
in your loop for each file.
Append something else, like a call to \Illuminate\Support\Str::random()
to get each name to be unique.
Depending on requirements, you might consider omitting the timestamp from the filename altogether and use something like md_file()
instead.
$name = implode('.', [
md5_file($file->getPathname()),
$file->getClientOriginalExtension()
]);
This can also help keep duplicate files off of your storage device.
Upvotes: 1