phplaravellaravel-medialibrary

Using spatie/media-library, how to rename a collection of uploaded files?


I would like to rename a collection of uploaded files, but when I use addAllMediaFromRequest() I can't retrieve information from the files.

In this example; I need to know the file extension in order to rename the file.

$files = $post->addAllMediaFromRequest();

$files->each(function (FileAdder $file) {
    $file->usingFileName(Str::random(16) . '.jpg')  // What if it's a png?
         ->toMediaCollection();
});

Solution

  • Since then, they have added the FileNamer class that allow to do what I was trying to achieve. You can can use your own class with the configuration.

    FileNamer.php

    namespace App;
    
    use Spatie\MediaLibrary\Support\FileNamer\DefaultFileNamer;
    
    class FileNamer extends DefaultFileNamer
    {
        public function originalFileName(string $fileName): string
        {
            return \Str::random(16);
        }
    }
    

    media-library.php

    /*
    * This is the class that is responsible for naming generated files.
    */
    'file_namer' => App\FileNamer::class,
    

    StoreFilesController.php

    $files = $post->addAllMediaFromRequest();
    
    $files->each(fn (FileAdder $file) => $file->toMediaCollection());