Back to Blog 2 min read

Choose Directories Based On Model In Media Library - Laravel

Hi everyone, today I'm going to something that I just learned this weekend. I was hacking on a side project and in upload I was using the Media Libra...

Hi everyone, today I'm going to something that I just learned this weekend. I was hacking on a side project and in upload I was using the Media Library (An Open Source Package By Spatie) in Laravel. I used this to store multiple product images.

Mentioned in this blog as well. File Upload Using Filepond In Laravel

When I used it for avatars it was directly creating directories storage/app/public/{model_id}/pic.png but in order cases I need something else. I wanted to create orders a directory and then model_id etc. So, I went to the documentation of the media library and then went to config/media-library.php a config file. There you'll get an option custom_path_generator => [] in which you can assign a generator class for Order Model.

And it started working. The below code snippet represents what I did. That you can use as a reference.

/*
     * Here you can specify which path generator should be used for the given class.
     */
    'custom_path_generators' => [
        // Model::class => PathGenerator::class
        Order::class => OrdersPathGenerator::class
        // or
        // 'model_morph_alias' => PathGenerator::class
    ],

I key you will have to pass the model name and in value the path generator class name.

This is my path generator class. I might be wrong in placing because I modified the method a little bit. But I can assure you that I worked for me and obviously will work for you as well.

<?php

namespace App\MediaLibrary;

use Spatie\MediaLibrary\Support\PathGenerator\PathGenerator;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class OrdersPathGenerator implements PathGenerator
{

    /*
     * Get the path for the given media, relative to the root storage path.
     */
    public function getPath(Media $media): string
    {
        return  $this->getBasePath($media);
    }

    /*
     * Get the path for conversions of the given media, relative to the root storage path.
     */
    public function getPathForConversions(Media $media): string
    {
        return $this->getBasePath($media) . '/conversions/';
    }

    /*
     * Get the path for responsive images of the given media, relative to the root storage path.
     */
    public function getPathForResponsiveImages(Media $media): string
    {
        return $this->getBasePath($media) . '/responsive-images/';
    }

    /*
     * Get a unique base path for the given media.
     */
    protected function getBasePath(Media $media): string
    {
        return 'orders/' . $media->getKey() . '/';
    }
}

Conclusion

I hope this blog will help you understand concept. And my whole efforts on this website will help you in somewhere in your code journey. Thanks for reading.