I want to delete a News from database and when I hit the delete button all data from database deleted but the image is remains in upload folder. So, how do I this to work. t
If you store your image in folder public, try this steps:
For example your image is sample.jpg and your path is public/img/sample.jpg so this codes will delete your image
use Illuminate\Support\Facades\File;
.
.
.
public function deleteImage(){
$imgWillDelete = public_path() . '/img/sample.jpg';
File::delete($imgWillDelete);
}
Using PHP unlink()
function, will have the file deleted
$path = public_path()."/uploads/".$from_db->image_name;
unlink($path);
The above will delete an image returned by $from_db->image_name
located at public/uploads
folder
For Delete files from the public folders, we can use the File::delete
function into the Laravel. For use File
need to use File
into the controller OR We can use \File
. This consider the root of the file.
// Delete a single file
File::delete($filename);
For delete Multiple files
// Delete multiple files
File::delete($file1, $file2, $file3);
Delete an array of Files
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
First, you should go to config/filesystems.php
and set 'root' => public_path()
like so:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path(),
],
Then, you can use Storage::delete($filename);
Two ways to delete the image from public folder without changing laravel filesystems config file or messing with pure php unlink function:
- Using the default local storage you need to specify public subfolder:
Storage::delete('public/'.$image_path);
- Use public storage directly:
Storage::disk('public')->delete($image_path);
I would suggest second way as the best one.
Hope this help other people.
This is the way I upload the file and save it into database and public folder and also the method I delete file from database and public folder.
this may help you and student to get complete source code to get the task done.
uploading file
at the first if you save file into database by giving pathpublic_path()
once it not need to used in delete method again
public function store_file(Request $request)
{
if($request->hasFile('file'))
{
$fileExtention = $request->file('file')->getClientOriginalExtension();
$name = time().rand(999,9999).$request->filename.'.'.$fileExtention;
$filePath = $request->file('file')->move(public_path().'/videos',$name);
$video = new Video_Model;
$video->file_path = $filePath;
$video->filename = $request->filename;
$video->save();
}
return redirect()->back();
}
deleting file
from database and public folder as you saved
public function delete_file(Request $request)
{
$file = Video_Model::find($request->id);
$file_path = $file->file_path;
if(file_exists($file_path))
{
unlink($file_path);
Video_Model::destroy($request->id);
}
return redirect()->back();
}