tattersoftware / codeigniter4-files

File uploads and management, for CodeIgniter 4
MIT License
61 stars 15 forks source link

Remove Files From Storage Directory #1

Closed rmcdahal closed 4 years ago

rmcdahal commented 4 years ago

I think the controller delete function code is incomplete as delete action will delete files from the database, but not from storage directory! or I am missing something?

MGatner commented 4 years ago

That's the current intention, as files can be linked to other tables. The plan is to have a command that will remove "orphaned" files that can be run on a cron (or however you like) and could serve as a template for writing your own so you can define what "orphaned" means.

I'm also open to an additional parameter to the model that will remove the file as well as the reference.

MGatner commented 4 years ago

The way routes work in CI4 you can also "intercept" anything you want because app/Config/Routes.php takes precedence so you could define your own delete() method in app/Controllers if you wanted that route to remove files as well.

rmcdahal commented 4 years ago

$file = $MediaModel->find($id); if (empty($file)) return redirect()->back(); $file_url = $this->config->storagePath .$file['upload_path'].'/'.$file['media_name']; $result = $MediaModel->delete($id); if($result = true){ if (is_readable($file_url) && unlink($file_url)) return redirect('admin/media')->with('message','Image Deleted Successfully From Database'); }else{ return redirect('admin/media')->with('message','Image Delete Errors'); } Is the perfect ways or any other recommendation ? Thanks

MGatner commented 4 years ago

That looks like a fine way to do it. Note that if you set your model return type to the file entity:

protected $returnType = 'Tatter\Files\Entities\File';

Then you can get the $file_url just by using $file->path:

$file = $MediaModel->find($id);
if (empty($file))
    return redirect()->back();
$result = $MediaModel->delete($id);
if ($result = true)
{
    if (is_readable($file->path) && unlink($file->path))
    return redirect('admin/media')->with('message', 'Image Deleted Successfully From Database');
}
else
{
    return redirect('admin/media')->with('message', 'Image Delete Errors'); 
}