How to Delete File using Form?

- 1 answer

Ad

I'm using OctoberCMS, based on Laravel.

I'm trying to delete a file. I enter the filename in a text box and press submit.

Component Form

<form method="POST" action="{{ url('/purge') }}">
    <input type="hidden" name="_handler" value="onPurge" />
    {{ form_token() }}
    {{ form_sessionKey() }}

    <input type="text" name="filename" /> 

    <input type="submit" name="submit" value="Purge" />  
</form>

Component PHP

public function onPurge(){
    $name = $_POST['filename'];

    if (!empty($_POST['submit'])) {
        $file->delete(storage_path("app/media/$name"));
    }
}

Error

Non-static method Illuminate\Database\Eloquent\Model::delete() should not be called statically

I tried

public function onPurge(){
    $name = $_POST['filename'];

    if (!empty($_POST['submit'])) {
        $file = new Video();
        $file->delete(storage_path("app/media/$name"));
    }
}

(also with full path /var/www/mysite/public/)

The function completes, No error, but the file does not delete.

Ad

Answer

Ad

Your purge function should be like,

public function onPurge(){
    $name = $_POST['filename'];
    $file_path = storage_path("app/media/$name");
    if(File::exists($file_path)){ // OR \File::exists($file_path)
     File::delete($file_path); // OR \File::delete($file_path)
    }
}

I feel it should work.

Give it a try.

Ad
source: stackoverflow.com
Ad