Hi there
I am trying to create an archiving system for media files that are updated. My client requires files to be kept for 3 years. There seems to be very limited documentation around making copies of files. Here is one link that seems to be what I need:
https://spatie.be/docs/laravel-medialibrary/v10/advanced-usage/moving-media
The problem is, they don't say what the structure of the "$anotherModel" should be. I tried creating a model, based exactly from my media table, it is removing the files from media, but wont do the copy.
This is what I use for the copy section in my controller:
$medias = $enrolment->media;
$media_archive = new MediaArchive();
foreach($medias as $media)
{
$movedMediaItem = $media->move($media_archive, 'new-collection', 'local');
}
and this is what my archive media model currently looks like:
<?php
namespace App\Models;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class MediaArchive extends Model implements HasMedia
{
use HasFactory;
use InteractsWithMedia;
public $table = 'media_archives';
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
protected $fillable = [
'model_type',
'model',
'uuid',
'collection_name',
'name',
'mime_type',
'disk',
'conversions_disk',
'size',
'manipulations',
'custom_properties',
'responsive_images',
'order_column',
'created_at',
'updated_at',
'deleted_at',
];
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
public function move(HasMedia $model, $collectionName = 'default', string $diskName = ''): self
{
$newMedia = $this->copy($model, $collectionName, $diskName);
$this->delete();
return $newMedia;
}
public function copy(HasMedia $model, $collectionName = 'default', string $diskName = ''): self
{
$temporaryDirectory = TemporaryDirectory::create();
$temporaryFile = $temporaryDirectory->path('/').DIRECTORY_SEPARATOR.$this->file_name;
/** @var \Spatie\MediaLibrary\MediaCollections\Filesystem $filesystem */
$filesystem = app(Filesystem::class);
$filesystem->copyFromMediaLibrary($this, $temporaryFile);
$newMedia = $model
->addMedia($temporaryFile)
->usingName($this->name)
->withCustomProperties($this->custom_properties)
->toMediaCollection($collectionName, $diskName);
$temporaryDirectory->delete();
return $newMedia;
}
}
Any assistance will be appreciated.