How to use a custom path with spatie media library plugin?
Anyone who has found how to use a custom directory structure with SpatieMediaLibraryFileUpload in a filament form? As stated in the filament manual, the directory() option doesn't work with SpatieMediaLibraryFileUpload.
I want to use this to create a directory structure per year and month for my attachments. So for example, instead of 'public/1/abc.jpg', it would be 'public/202411/1/abc.jpg'
In spatie media library there's an option to use a path generator as described here: https://spatie.be/docs/laravel-medialibrary/v11/advanced-usage/using-a-custom-directory-structure
But I can't get this to work inside the filament plugin because the path generator functionality seems to be missing from the plugin. Any ideas?
Using a custom directory structure | laravel-medialibrary
laravel-medialibrary
9 Replies
I assume 202411 is Ym ?
Spatie has a per-model path generator AFAIK. In the config there's the following section
I haven't used it but I assume you can define a custom path generator based on the related model that the media is linked to.
Personally, I'm using a custom media model (extends the default Spatie media model) and added my own way to override the generated path
So in the above example, if your
Media
Model is linked to a user, you would have something like
As I said, I haven't tried it but it should work.@toeknee Yes, it is Ym.
@ChesterS Thanks for sharing this, but after installing filament/spatie-laravel-media-library-plugin there is not even a config file for the media-library. So I guess this plugin simply does not have all functionality of the complete spatie media library. I also tried to override the Media model and use a getPath function like this:
public function getPath(string $conversionName = ''): string
{
// Define path structure, for instance: 'images/YYYYmm/media_id'
Log::info('Media getPath() called');
return 'images/' . now()->format('Y') . now()->format('m') . '/' . $this->getKey() . '/';
}
But my log message never appears in the log, so I gues that's also not an option.The config is part of
spatie-media-library
, not the plugin. You can publish it with
You need that to override the path generator or use a custom model
@ChesterS Thanks for pointing me in the right direction! It works now! After publishing the config, I tested with a custom generator per model and it worked. For my case however I just created one CustomPathGenerator that creates a subfolder per model and per Ym. I made a gist for it: https://gist.github.com/EmmArro/ba5b67986585550b140ee64554902135
Gist
Custom path generation
Custom path generation. GitHub Gist: instantly share code, notes, and snippets.
Cool, it's similar to what I did. Just a tip, you don't have to re-implement every method, you can just extend the base name generator and just override the
getPath()
methodYes, you're right, thanks 👍