简体   繁体   中英

Spatie Medialibrary Custom Custom Directory As Prefix

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

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM