简体   繁体   中英

spatie/laravel-medialibrary - Ability to add conversion per media model "on the fly"?

I'm using popular package spatie/laravel-medialibrary for associating files with models.

I was wondering if there is possibility add conversions on the fly, right before adding media to model.

I tried something like this, but it seems like conversions are being ignored if they are added this way.


// $this being the model with HasMedia interface and InteractsWithMedia trait

use Spatie\MediaLibrary\Conversions\Conversion;

$this->mediaConversions = [
  Conversion::create('name')
      ->withResponsiveImages()
      ->performOnCollections('default')
      ->format('webp'),
  
  Conversion::create('another-one')
      ->withResponsiveImages()
      ->performOnCollections('default')
      ->format('webp'),
];

$this->addMedia($filePath)->toMediaCollection();

Is this somehow possible to do?

Something like this would be nice:

$model->addMedia($path)->withConversions([
  Conversion::create('another-one')
      ->withResponsiveImages()
      ->performOnCollections('default')
      ->format('webp'),
])

But withConversions doesn't exist in v10

Thank you for answering.

You can register the image conversion directly in the model as described in the documentation here .

To generate that thumbnail, you must add a conversion like this one to your model.

use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

public function registerMediaConversions(Media $media = null): void
{
    $this
        ->addMediaConversion('preview')
        ->fit(Manipulations::FIT_CROP, 300, 300)
        ->nonQueued();
}

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