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

Asinox
Asinox

Hello guys, I'm cloning a model with the relationships as well, everything is fine until replicate the attachments.

This works fine: $new = $model->replicate(); And if i need a relationship, this works too: $model->realstate->replicate(); But the replicate() dont work with attachments: $model->images->replicate();

Any idea about how to clone / replicate the attachment model?

Thank you

Bhargav
Bhargav

Did you find how to do this?

blaz
blaz

In case you need to duplicate attachment files, here is an example for attachOne and attachMany:

`public function onDuplicate() { $checked_items_ids = input('checked');

    $images = array_merge(
        array_keys((new YourModel())->attachOne),
        array_keys((new YourModel())->attachMany)
    );

    foreach ($checked_items_ids as $id) {
        $original = YourModel::where("id", $id)->with($images)->first();

        $clone = $original->replicate();

        $clone->sort_order = null;
        $clone->date_end = null;
        $clone->finished = 0;
        $clone->created_at = Carbon::now();
        $clone->updated_at = Carbon::now();

        $clone->save();

        $this->cloneImages($clone, $original, $images);
    }

    Flash::success('Auction cloned');
    return $this->listRefresh();
}

private function cloneImages(Auction $clone, Auction $original, array $images)
{
    foreach ($images as $image) {
        $fileModel = new \System\Models\File;
        $temp = $original->{$image};

        if (is_null($temp)) {
            continue;
        }

        if (is_a($temp, Collection::class)) {
            $temp->each(function($item) use ($image, $clone) {
                $fileModel = new \System\Models\File;
                $clone->{$image}()->save($fileModel->fromFile($item->getLocalPath()));
            });
        } else {
            $clone->{$image}()->save($fileModel->fromFile($temp->getLocalPath()));
        }
    }

    return $clone;
}

` Depends on your use case. You can put this into queue to speed up processing for the end-users.

Last updated

1-3 of 3

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