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

1.1k Views Asked by At

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.

2

There are 2 best solutions below

1
user2682025 On

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();
}
1
Wheeler Flemming On

You can use model properties in conversions according to the docs:

https://spatie.be/docs/laravel-medialibrary/v10/converting-images/defining-conversions

// in your model
public $registerMediaConversionsUsingModelInstance = true;

public function registerMediaConversions(Media $media = null): void
{
    $this->addMediaConversion('thumb')
          ->performOnCollections('images', 'downloads')
          ->width($this->width)
          ->height($this->height);
}