diff --git a/src/Actions/Blogs/StoreBlogCoverAction.php b/src/Actions/Blogs/StoreBlogCoverAction.php index c7dd39a..67b536f 100644 --- a/src/Actions/Blogs/StoreBlogCoverAction.php +++ b/src/Actions/Blogs/StoreBlogCoverAction.php @@ -4,6 +4,8 @@ use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; +use SethSharp\BlogCrud\Models\Blog\Blog; +use SethSharp\BlogCrud\Actions\Files\DeleteS3File; class StoreBlogCoverAction { @@ -15,7 +17,7 @@ class StoreBlogCoverAction * @param string $path * @return string */ - public function __invoke(UploadedFile $file, int $blogId, string $path = '/cover-images/'): string + public function __invoke(UploadedFile $file, Blog $blog, string $path = '/cover-images/'): string { $newFile = config('blog-crud.image_driver')->read($file)->scale(500, 500)->encode(); @@ -24,10 +26,15 @@ public function __invoke(UploadedFile $file, int $blogId, string $path = '/cover $filename = uniqid() . '_' . $file->getClientOriginalName(); - $path = $structure . 'blogs/' . $blogId . '/cover-images/' . $filename; + $path = $structure . 'blogs/' . $blog->id . '/cover-images/' . $filename; Storage::disk('s3')->put($path, $newFile); + // destory previous cover image + if ($blog->cover_image) { + app(DeleteS3File::class)($blog->cover_image); + } + return $path; } } diff --git a/src/Actions/Blogs/UpdateBlogAction.php b/src/Actions/Blogs/UpdateBlogAction.php index d9bce08..b73a3cd 100644 --- a/src/Actions/Blogs/UpdateBlogAction.php +++ b/src/Actions/Blogs/UpdateBlogAction.php @@ -76,7 +76,7 @@ public function __invoke(Blog $blog, UpdateBlogRequest $updateBlogRequest): Blog // upload cover image $coverImagePath = $blog->cover_image; if ($coverImage = $updateBlogRequest->file('cover_image')) { - $coverImagePath = app(StoreBlogCoverAction::class)($coverImage, $blog->id); + $coverImagePath = app(StoreBlogCoverAction::class)($coverImage, $blog); } // dynamically update model with validated data diff --git a/src/Actions/Files/DeleteS3File.php b/src/Actions/Files/DeleteS3File.php new file mode 100644 index 0000000..46a5269 --- /dev/null +++ b/src/Actions/Files/DeleteS3File.php @@ -0,0 +1,27 @@ +delete($path); + + return true; + } catch (Exception $e) { + + return false; + } + } +} diff --git a/src/Actions/Files/DestroyFileAction.php b/src/Actions/Files/DestroyFileAction.php index fd2f2a6..cb1cac1 100644 --- a/src/Actions/Files/DestroyFileAction.php +++ b/src/Actions/Files/DestroyFileAction.php @@ -16,13 +16,6 @@ class DestroyFileAction */ public function __invoke(File $file): bool { - try { - Storage::disk('s3')->delete($file->path); - - return true; - } catch (Exception $e) { - - return false; - } + return app(DeleteS3File::class)($file->path); } }