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.
<?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
@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');
}
}