tobz.nz's avatar

Spatie/media-library is is possible to move file to another disk?

I'm migrating files from one cloud service to another - is there an easy way to copy the files and update the DB? I don't want to create new Db records but update the existing ones.

Spaties "extensive" documentation is quite lacking in some areas (Love your work Spatie, Honest)

Ideally something like:

$media->copyToDisk('new-disk', 'optional-new-collection');
0 likes
6 replies
davidifranco's avatar

@tobz.nz - The move command will create new DB records. It will also delete the old DB records and DELETE the original media.

from Spatie\MediaLibrary\MediaCollections\Models\Media.php;

public function move(HasMedia $model, $collectionName = 'default', string $diskName = '', string $fileName = ''): self
    {
        $newMedia = $this->copy($model, $collectionName, $diskName, $fileName);

        $this->delete();

        return $newMedia;
    }

I would suggest using the copy method first as it leaves the original files intact, then once your operation is complete, delete any DB media records that have the old disk name.

tobz.nz's avatar
tobz.nz
OP
Best Answer
Level 3

Thanks guy - I did look at both those methods, but I really need to keep the existing DB records(ids).

I ended up writing a command to just copy the files to thhe new disk, then update the disk name in the DB.

2 likes
ahmedde's avatar

We're still doing "Thanks guys I solved it"? 😭 Can you post your solution? thanks

TheECGaming's avatar

To anyone who comes here later (as I did because it's the top result in Google). Here's a command I built to migrate. All it does it check the disk of the media items, and move any that aren't in the correct disk.

Note that it uses all(), which if you have a LOT should be changed. Just did this as I set up a new site, forgot to change disk from local to s3, and only had like 5 images uploaded.

Please or to participate in this conversation.