Laravel storage folder in image upload and old image delete
This tutorial is for the Laravel storage folder in image upload and old image delete. Laravel in creating a storage folder this command $ php artisan storage:link
. and you can store images in the storage folder. but I will cover the storage folder’s old image on how to remove it.
Laravel image uploading is quite simple and you can upload multiple images and store them in the database. Sometimes, we require to upload or remove images of any existing record. In that case, we update the new images and remove the old image from the database.
In this tutorial, I will give an example of How to delete the previous image from the storage folder when updated by the new image in Laravel. I will give you two ways to delete images or files from the public folder. One is using Storage::delete and other is File::delete() predefined function.
Also read: How to display the storage folder image in laravel?
<input type="image" name="tiles_image">
<input type="hidden" id="old_image" value="abc.png">
Simple you can controller in use :
if($request->hasFile('file_name')) {
$name = strtolower($request->file('file_name')->getClientOriginalName());
$file_name = time().'_'.$name;
$path = $request->file('file_name')->storeAs('public/uploads',$file_name);
$model->file_name = $file_name;
$Image = str_replace('/storage', '', $request->old_image);
#Using file
if( File::exists(public_path('uploads/' . $Image)) ) {
Files::delete(public_path('uploads/' . $Image));
}
#Using storage
if(Storage::exists('uploads/' . $Image)){
Storage::delete('/public/uploads/' . $Image);
}
} else {
$model->file_name = $request->file_name_old;
}