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

vincent15000's avatar

Spatie media library - How to customize the directories ?

Hello,

I'm searching for hours but I don't find any solution.

I'm using the Spatie media library and I'd like to change the default folders in which the medias are stored.

Instead of having the media id as the folder name, I'd like to have the user id to which the media is associated. The aim is that all media associated to a specific user are stored in the same folder.

I have seen the interface to customize the directories structure, but I'm not sure that it's the solution for me because I need several different folders according to the users ids.

https://spatie.be/docs/laravel-medialibrary/v10/advanced-usage/using-a-custom-directory-structure

Can you help me please ?

Thanks a lot.

V

0 likes
10 replies
vincent15000's avatar

@Sinnbeck I have tried this.

<?php

namespace App\Services;

use Spatie\MediaLibrary\Support\PathGenerator\PathGenerator as BasePathGenerator;
use App\Models\Media;

class MediaPathGenerator implements BasePathGenerator
{
	public function getPath(Media $media): string
	{
		return $media->user->id.'/'.$media->id.'/';
	}

	public function getPathForConversions(Media $media): string
	{
		return $media->user->id.'/'.$media->id.'/conversions/';
	}

	public function getPathForResponsiveImages(Media $media): string
	{
		return $media->user->id.'/'.$media->id.'/responsive/';
	}
}

But I get this error and I don't understand why I get this error because I return a string (as required).

Declaration of App\Services\MediaPathGenerator::getPath(App\Models\Media $media): string must be compatible with Spatie\MediaLibrary\Support\PathGenerator\PathGenerator::getPath(Spatie\MediaLibrary\MediaCollections\Models\Media $media): string
vincent15000's avatar

@Sinnbeck Yes I am passing a custom model which extends the spatie media model, so I can add my own relationships.

'media_model' => App\Models\Media::class,
...
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;
use App\Models\User;

class Media extends BaseMedia
{
    use HasFactory;

    public function user()
    {
        return $this->morphTo(__FUNCTION__, 'model_type', 'model_id');
    }
}
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@vincent15000 I would assume it automatically injects the correct one if you typehint it as suggested in the interface

1 like
bestmomo's avatar

You can use registerMediaConversions (with addMediaConversion) to define a custom folder, look here.

1 like

Please or to participate in this conversation.