advanced-nova-media-library
advanced-nova-media-library copied to clipboard
Images are being storing for each in sperate folder
advanced-nova-media-library version = 3.4 when I upload any image it saved in separated folder in public. this named with number.
if I upload another one the file name will be named with increments number
how can I let them all in one folder
@ebess
@OthmanAlseagh This part has to do with Spatie's package, so check their documentation. Current package has nothing to do with it.
https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-a-custom-directory-structure
I went with something like this, wanting to not have too many directories/files in one directory to prevent performance issues down the road, and to store per model I am morphing.
{model_type}/YY/MM/DD/{model_id}/{media_uuid}
then after that it has the "sanatized?" file name from the upload which I can't seem to modify, ideally would have had that be the uuid or id of the media record...
<?php
namespace App\Support;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Support\PathGenerator\DefaultPathGenerator;
use Str;
class CustomMediaPathGenerator extends DefaultPathGenerator
{
/*
* Get a unique base path for the given media.
*/
protected function getBasePath(Media $media): string
{
$prefix = config('media-library.prefix', '');
// https://stackoverflow.com/questions/2211197/how-should-i-format-user-uploaded-pictures-filenames
$datePath = Str::of($media->created_at->format('Y-m-d'))->replace('-', DIRECTORY_SEPARATOR)->value;
$key = $media->model_type.DIRECTORY_SEPARATOR.$datePath.DIRECTORY_SEPARATOR.$media->model_id.DIRECTORY_SEPARATOR
.$media->uuid; // $media->getKey();
if ($prefix !== '') {
return $prefix.'/'.$key;
}
return $key;
}
}
And set it in the media-library.php config to use that generator. Seems like can't put all files in one directory like public/model/ because media library deletes them all. So need a unique directory for each media uploaded.
Additionally could not find a nice way to programmatically change the filename on disk/storage but keep original name in DB table. Ideally would have the uuid or id as the file name.
I also did not want to use long class names in the morphsMany model_type columns and other morph relationships so I added this to my AppServiceProvider think it is nicer to use smaller amount of data than large string that could change on refactor more likely.
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Relation::morphMap([
1 => 'App\Models\User',
2 => 'App\Models\Payment',
3 => 'App\Models\Store',
4 => 'App\Models\Order',
8 => 'App\Models\Listing',
]);
}