Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bearbytestudio's avatar

Spatie Media Library: Can I add a custom path generator, then update all old media to reflect the new structure easily?

I have been using a custom path structure for my media for a little while, but I've realised it's wrong and it's making things tricky so needs updating. I've added a new CustomPathStructure class for all media going forwards. Is there a way I can easily update all of my old media files to use this new structure? I've noticed php artisan media-library:regenerate doesn't handle that.

0 likes
5 replies
SilenceBringer's avatar

@iamstuart I don't think so. I think you need to move existing files manually (write custom script) to follow new structure

SilenceBringer's avatar
Level 55

@iamstuart hm... something like


$oldPathGenerator = app(OldPathGenerator::class); // init your old path generator

$medias = Media::where('id', '<', $lastIdOfMediaCreatedWithOldPathGenerator); // get medias to move

foreach ($medias as $media) {
	Storage::move(
		$oldPathGenerator->getPath($media) . $media->file_name, // path from old generator
		$media->getPath() . $media->file_name, // generate path with the current (new) generator
	);
}

also you can move entirely folder with old files to new place.

1 like
bearbytestudio's avatar

@SilenceBringer Superstar! I only needed to tweak it slightly to:

$oldPathGenerator = app(OldPathGenerator::class); // init your old path generator
$newPathGenerator = app(NewPathGenerator::class); // init your old path generator

$medias = Media::where('id', '<', $lastIdOfMediaCreatedWithOldPathGenerator); // get medias to move

foreach ($medias as $media) {
	Storage::move(
		$oldPathGenerator->getPath($media) . $media->file_name, // path from old generator
		$newPathGenerator->getPath($media) . $media->file_name, // generate path with the current (new) generator
	);
}

Please or to participate in this conversation.