From 40b629d35d3f09fd66226a0e62999ef587b95d5f Mon Sep 17 00:00:00 2001 From: Dan Brown Date: Sun, 23 Aug 2015 14:05:09 +0100 Subject: [PATCH] Fixed image folder deletion. Fixes #22. --- app/Http/Controllers/ImageController.php | 28 +++++++++++++++++++----- app/Http/routes.php | 1 + 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/app/Http/Controllers/ImageController.php b/app/Http/Controllers/ImageController.php index 9fcd5c304..aa8cc9ee8 100644 --- a/app/Http/Controllers/ImageController.php +++ b/app/Http/Controllers/ImageController.php @@ -177,14 +177,30 @@ class ImageController extends Controller // Delete files $folder = public_path() . dirname($image->url); - $pattern = '/' . preg_quote(basename($image->url)). '/'; - $dir = new RecursiveDirectoryIterator($folder); - $ite = new RecursiveIteratorIterator($dir); - $files = new RegexIterator($ite, $pattern, RegexIterator::ALL_MATCHES); - foreach($files as $path => $file) { - unlink($path); + $fileName = basename($image->url); + + // Delete thumbnails + foreach(glob($folder . '/*') as $file) { + if(is_dir($file)) { + $thumbName = $file . '/' . $fileName; + if(file_exists($file)) { + unlink($thumbName); + } + // Remove thumb folder if empty + if(count(glob($file . '/*')) === 0) { + rmdir($file); + } + } } + + // Delete file and database entry + unlink($folder . '/' . $fileName); $image->delete(); + + // Delete parent folder if empty + if(count(glob($folder . '/*')) === 0) { + rmdir($folder); + } return response()->json('Image Deleted'); } diff --git a/app/Http/routes.php b/app/Http/routes.php index a6cda78e6..a3db08a0d 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -70,6 +70,7 @@ Route::group(['middleware' => 'auth'], function() { Route::get('/images/all', 'ImageController@getAll'); Route::put('/images/update/{imageId}', 'ImageController@update'); Route::delete('/images/{imageId}', 'ImageController@destroy'); + Route::get('/images/{imageId}/delete', 'ImageController@destroy'); Route::get('/images/all/{page}', 'ImageController@getAll'); Route::get('/images/{any}', 'ImageController@getImage')->where('any', '.*');