Created
June 11, 2025 19:19
-
-
Save NazemMahmud/9bef6402f3b0231e532eebda375741bd to your computer and use it in GitHub Desktop.
Laravel: Image migration after file download
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Services; | |
| use App\Services\FileDownloadService; | |
| use Illuminate\Http\UploadedFile; | |
| class ImageMigrationService | |
| { | |
| /** | |
| * follow this gist: https://gist.github.com/NazemMahmud/c13bcaff9d7bc6711adad6f348d42064 | |
| */ | |
| private FileDownloadService $downloadService; | |
| public function __construct(FileDownloadService $downloadService) | |
| { | |
| $this->downloadService = $downloadService; | |
| } | |
| public function migrateImageFromUrl(string $imageUrl, string $uploadPath = 'images'): array | |
| { | |
| $uploadedFile = null; | |
| try { | |
| // Download the image | |
| $uploadedFile = $this->downloadService->downloadImageFile($imageUrl); | |
| // Upload to your storage | |
| $result = $this->uploadToStorage($uploadedFile, $uploadPath); | |
| return $result; | |
| } finally { | |
| // Clean up temporary file | |
| if ($uploadedFile && file_exists($uploadedFile->getPathname())) { | |
| unlink($uploadedFile->getPathname()); | |
| } | |
| } | |
| } | |
| /** | |
| * this is a sample example, your upload code might be different based on your requirements | |
| * such as, you might want to upload in aws s3 storage, so upload method would be different for you | |
| */ | |
| private function uploadToStorage(UploadedFile $file, string $path): array | |
| { | |
| // Your upload logic here | |
| $filename = time() . '_' . $file->getClientOriginalName(); | |
| $storedPath = $file->storeAs($path, $filename, 'public'); | |
| return [ | |
| 'success' => true, | |
| 'path' => $storedPath, | |
| 'url' => asset('storage/' . $storedPath), | |
| 'filename' => $filename | |
| ]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment