'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 1:[1]

To get a file extension within laravel:

$request->file('photo')->extension()

To create new file name:

        $newFileName = Str::random(20) .'.'.$request->file('photo')->extension();

don't forget to import Str class.

then you could rename the uploaded file before storing it easily

            $item->addMedia($request->photo)->usingFileName($newFileName)->toMediaCollection('photo');

code tested Laravel v9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hussam Adil