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

Tschallacka
Tschallacka

Sometimes you want to copy a File upload object into a new model without re-uploading the file. Just copy it over in a new model(well maybe i'm the only one who wants to do that, but hey, then this is for my future self :P)

You need to make sure you get the proper File class loaded, I prefer to use use, but you can also just use the full path for the object. whatever has your fancy :-)

use System\Models\File;

My example takes place in a function in my model, I called duplicate. In the model I have a field called webicon that is a attachOne

 public $attachOne = ['webicon' => ['System\Models\File',]];

I have in that model a function called duplicate, because i regularly need to duplicate that model. In that model, for the webicon I have the following code

public function duplicate() {
     $new = new MyCustomModel();
    // So many ways to do this, there are probaly better ways to do this... 
    // but this howto isn't about this xD
    foreach($this->fillable as $value) {
        $new->{$value} = $this->{$value};
        }
    // We create a new File object
    $x = new File();
    // If there's a webicon attached to the model
    if($this->webicon != null) {
         // we use DIRECTORY_SEPERATOR to make sure we are OS independant.
        $x = $x->fromFile(base_path().
                                              DIRECTORY_SEPARATOR.
                                              'storage'.
                                              DIRECTORY_SEPARATOR.
                                              'app'.
                                              DIRECTORY_SEPARATOR.
                                              $this->webicon->getDiskPath()
                                          );
        // Copy over the original uploaded file name
        $x->file_name = $this->webicon->file_name;
        // Copy over the custom title if that was set
        $x->title = $this->webicon->title;
        // Copy over the custom description if that was set
        $x->description = $this->webicon->description;
        // This is the magic part :-) acutally attach the file.
        $new->webicon()->setSimpleValue($x);
    }
return $new;
}

Last updated

1-1 of 1

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