possible "duplicate": Laravel - Delete images from storage / update post
I want laravel to delete the old image and replace it with new uploaded image in the edit form. I tried doing this:
if( $request->hasfile('violationStatement') ) {
$destination = 'violations/' . $violation->violationStatement;
// Deletes the file if it exists
if( File::exists($destination) ) {
File::delete($destination);
}
$file = $request->file('violationStatement');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('violations/', $filename);
$violation->violationStatement = $filename;
}
$violation->update();
But the image is not deleted nor updating. In addition, I want to have a condition when I just want to edit data without uploading new image...
CodePudding user response:
First make sure of namespace
use Illuminate\Support\Facades\File;
Then edit $violation->update() to $violation->save();
And if the path in public folder use this method public_path() as this
$destination = public_path('violations/' . $violation->violationStatement);
But if the path in storage folder use this method storage_path() as this
$destination = storage_path('violations/' . $violation->violationStatement);
CodePudding user response:
I use Intervention\Image\Facades\Image
for uploading image And Illuminate\Support\Facades\File
For Manage Directories. below Code replace Pic If Exist. think now you have 123.jpg
and you want replace it. it replace old pic with new one. if your image name is difference you can delete old one.
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
//Get Data Of uploaded pic
$file = $request->file('violationStatement');
$srcPath = $file->getRealPath();
$size = $file->getSize(); // if You Need Pic Size
$extension = $file->getClientOriginalExtension();
//Start Uploading
$Image = Image::make($srcPath);
$destPath = public_path("violations");
File::ensureDirectoryExists($destPath); // Check Directory Exist Or Make
$filename = time() . '.' . $extension;
$Image->save($destPath.'/'.$filename);
at last I suggest add some unique thing to Your Image Name because it may two user upload picture at Same Time!!! and One Picture replaced.