Matt McManis
Matt McManis

Reputation: 4675

How to Delete File using Form?

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.

Upvotes: 0

Views: 652

Answers (2)

Rahul
Rahul

Reputation: 18557

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.

Upvotes: 1

Sam Aldis
Sam Aldis

Reputation: 36

You can use the php function unlink instead.

if (!empty($_POST['submit'])) {
    $removed = unlink($path . $file);
}if(!$removed) {
   die('file could not be deleted');
}

Upvotes: 1

Related Questions