"Trying to get property of non-object" when uploading a file that isn't saved

- 1 answer

Ad

I have a model with has a file relationship that uses OctoberCMS's system_files.

public $attachOne = [
    'return_file' => ['System\Models\File', 'public' => false, 'delete' => true]
    ];

In the fields.yaml I have the form

   return_file:
        label: Attach File
        type: fileupload
        mode: file
        span: right

Now before or after I save this, I want to move the image from its directory to a custom one in my plugin. afterSave() doesn't seem to retrieve the file path to move it.

However in system_files I see that in MySQL workbench has in fact uploaded it.enter image description here

Yet when I hit save in the backend I get "Trying to get property of non-object"

Here is what is in the afterSave() function.

public function afterSave()

{

$custom_path = plugins_path() . '/acme/request/uploads/';
$file = $this->return_file->getPath();
$move_file = $file->move($custom_path);

}

Is it possible to even upload in the backend and move the file before/after saving?

Ad

Answer

Ad

The problem is the file doesn't fully exist yet in afterSave(), it exists still as a deferred binding. Try this instead:

$this->return_file()->withDeferred($this->sessionKey)->first()->getPath();
Ad
source: stackoverflow.com
Ad