jeudi 2 avril 2020

Uploading files to specific folders depending on their models with Laravel(5.5) Media Library

I would like to upload files to specific folder according to their models using Laravel(5.5) Media Library, for instance: I have a Lesson model with a relation to Course model(a lesson belongs to a course), which uploads all files successfully to "storage/app/public/lessons" using media library, but now I would like to upload these files to something like "storage/app/public/{course_slug}/{lesson_slug}/{file}". How can I accomplish that?

So far I have tried to set a CustomPathGenerator to check if $media is a instance of Lesson, and then get the course slug and lesson slug, but I dont think it works like that.

This is what is working so far.

<?php

namespace App\Handlers;

use App\Lesson;
use Spatie\MediaLibrary\Media;
use Spatie\MediaLibrary\PathGenerator\PathGenerator;

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

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

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

in my Lesson model I only tell to upload

.....

public function setDocumentsAttribute($input){

  foreach ($input as $file) {
     $this->addMedia(storage_path('tmp/uploads/' . $file))->toMediaCollection('documents');
  }

}

.....


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire