This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

lucas.sanner54070
lucas.sanner54070

I can't figure out how to delete properly an uploaded file.

In my model:

...

public $attachMany = [
     'attestations' => ['System\Models\File', 'order' => 'created_at desc', 'delete' => true]
];

...

In my controller:

...

public function update_onDeleteFile($recordId = null)
{   
    $data = post();
    $member = Member::find($recordId);
    $member->attestations()->where('id', $data['file_id'])->delete();
}

...

The model seems being deleted correctly (ie: the row no longer exists in the system_files table). But the physical file is still there in the storage directory. storage/app/uploads/public/5ff/56e/945/5ff56e9452a45600617548.pdf

How can I remove the model and the file at once ?

mjauvin
mjauvin

try detach() instead of delete()

lucas.sanner54070
lucas.sanner54070

mjauvin said:

try detach() instead of delete()

I get an error: Call to undefined method

mjauvin
mjauvin

The FileUpload widget has this method:

    public function onRemoveAttachment()
    {   
        $fileModel = $this->getRelationModel();
        if (($fileId = post('file_id')) && ($file = $fileModel::find($fileId))) {
            $this->getRelationObject()->remove($file, $this->sessionKey);
        }
    }

So that should be done automatically when you remove the relation, no? Otherwise, just clone this behavior in your ajax handler...

lucas.sanner54070
lucas.sanner54070

I'm not sure...
According to the October\Rain\Database\Attach\File class:

/**  
 * After model is deleted
 * - clean up it's thumbnails
 */
public function afterDelete()
{    
    try {
        $this->deleteThumbs();
        $this->deleteFile();
    }
    catch (Exception $ex) {
    }
}   

...

/**
 * Delete file contents from storage device.
 * @return void
 */
protected function deleteFile($fileName = null)
{
    if (!$fileName) {
        $fileName = $this->disk_name;
    }

    $directory = $this->getStorageDirectory() . $this->getPartitionDirectory();
    $filePath = $directory . $fileName;

    if ($this->storageCmd('exists', $filePath)) {
        $this->storageCmd('delete', $filePath);
    }

    Cache::forget($this->getCacheKey($filePath));
    $this->deleteEmptyDirectory($directory);
}

The file should be removed the from the server don't you think ?
May be I might as well use unlink('path/to/file') just after deleting the model ?

lucas.sanner54070
lucas.sanner54070

I think I got it.
It's actually very subtle.

Deletes only the model.

$data = post();
$member->attestations()->where('id', $data['file_id'])->delete();

Deletes both the model and the file.

$data = post();
$file = $member->attestations()->where('id', $data['file_id'])->first();
$file->delete();

Hope it helps.

1-6 of 6

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.