1

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.

apokryfos
  • 38,771
  • 9
  • 70
  • 114

2 Answers2

0

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();
}
user2682025
  • 656
  • 2
  • 13
  • 39
  • Thanks for your answer, but that's not what I'm asking. I know you should do media conversions via model preparing, but I need to create conversions dynamically before adding media to model. The example provided in the question is simplified, the actual use case is more complex. – Adam Ondrejkovič Dec 02 '22 at 09:40
0

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);
}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 28 '23 at 05:13