Simple upload file laravel
Field Database:
UploadController:
php
$table->string('image');
php
private array $fileFields = ['image']; // Save images for store foreach ($this->fileFields as $row) { if ($request->hasFile($row)) { $data[$row] = $this->saveFiles($request->file($row)); } } // Remove and Edit files for update foreach ($this->fileFields as $row){ if($request->hasFile($row)){ $this->removeFileFromStorage($files->$row); $data[$row] = $this->saveFiles($request->file($row)); } } // Remove for destroy foreach ($this->fileFields as $row){ $this->removeFileFromStorage($files->$row); } /** * Save Files */ private function saveFiles($file) { $fileName = time() . '_' . $file->getClientOriginalName(); $path = $file->storeAs('files/file', $fileName, 'public'); return Storage::url($path); } /** * Remove Files in Route Storage Public */ private function removeFileFromStorage($file) { $path = str_replace('/storage/', '', $file); if (Storage::disk('public')->exists($path)){ Storage::disk('public')->delete($path); } }
bash
php artisan storage:link
commit 59b95bf
nice and compact. one thing i'd watch: time() + the original name can collide if two uploads with the same filename land in the same second. have you tried $file->store() with the hashed name instead?