Spatie Medialibrary Custom Custom Directory As Prefix

Viewed 2930

I am using spatie/laravel-medialibrary:8.0.

When I uploaded file, it was saved in storage/public directory.

1/filename.file_extension, 2/filename.file_extension...

I think 1, 2... are ids of files.

Is there any way to put different prefix directory according to user?

For example, I want to put like this.

public/storage/user_id/1/filename.file_extension, 

I searched about it but couldn't find exact answer,

Can anyone help me?

Thanks

1 Answers

The way to go it's under docs Using a custom directory structure.

To override the default folder structure, a class that conforms to the PathGenerator-interface can be specified as the path_generator in the config file.

For example, you can create a new class that extends that interface and return some path for your models

class CustomPathGenerator implements PathGenerator
{
    public function getPath(Media $media) : string
    {
        if ($media instanceof Post) {
            return 'user_id/' . $media->user_id . '/' . $media->id;
        }
        return $media->id;
    }

    public function getPathForConversions(Media $media) : string
    {
        return $this->getPath($media) . 'conversions/';
    }

    public function getPathForResponsiveImages(Media $media): string
    {
        return $this->getPath($media) . 'responsive/';
    }
}

Then update the config file and point to that class:

'path_generator' => CustomPathGenerator::class,

References:

spatie/laravel-medialibrary Docs Using a custom directory structure.

Laracasts Spatie MediaLibrary default storage depending on the model "best answer".

Related