Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

How to Generate Image Conversions with Spatie Laravel Media Library

In a Laravel project, Spatie Media Library can create smaller or reformatted images from files attached to an Eloquent model. A conversion is a named version of an original file that the package generates, such as a thumbnail or a WebP image. Define conversions on the model, and the package generates them when you add media.

To create one, make the model implement Media Library’s HasMedia interface, use its InteractsWithMedia trait, and define a conversion in registerMediaConversions. The package handles the image work and, by default, queues conversion jobs so they do not have to run during the upload request.

Define a conversion on the model

Add a conversion method to the model that owns the uploaded image. For example, this model creates a thumbnail with set dimensions:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class Product extends Model implements HasMedia
{
    use InteractsWithMedia;

    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(368)
            ->height(232);
    }
}

addMediaConversion gives the generated image its name. The width and height methods set its dimensions. Media Library also supports operations such as sharpening, cropping, adding a border, and applying a sepia effect. See the conversion definition options for the available methods.

Attach an image to the model as usual. For example, a controller can add an uploaded file to the model’s images collection:

$product
    ->addMediaFromRequest('image')
    ->toMediaCollection('images');

The collection groups media attached to the model. After the package generates the conversion, use the collection and conversion names to retrieve its URL:

$product->getFirstMediaUrl('images', 'thumb');

You can register several conversions in the same method, each with its own name and transformations. Use performOnCollections when a conversion should run only for media in a particular collection:

$this->addMediaConversion('thumb')
    ->width(368)
    ->height(232)
    ->performOnCollections('images');

Choose the output format and storage disk

Conversions are saved as JPEG by default. To request WebP, set the format in the conversion definition:

$this->addMediaConversion('web')
    ->width(1200)
    ->format('webp');

To preserve the original image’s format, use keepOriginalImageFormat() instead. The package documents automatic conversion support for common image formats, including JPEG, PNG, SVG, WebP, and AVIF, along with some non-image media types. Check the supported conversion behavior if your uploads include formats beyond common web images.

By default, a conversion uses the same disk as its original media file. Call storeConversionsOnDisk to store generated files elsewhere:

$this->addMediaConversion('thumb')
    ->width(368)
    ->height(232)
    ->storeConversionsOnDisk('public');

You can also assign a disk to a whole collection with useDisk. Choose a disk that the conversion job and browsers requesting the image can access.

Decide when conversions run

Media Library queues conversions by default. A queue worker must be running to process those jobs; until it does, the conversion URL may not point to a generated file. Use nonQueued() when you want a conversion to run synchronously as media is added:

$this->addMediaConversion('thumb')
    ->width(368)
    ->height(232)
    ->nonQueued();

Synchronous work keeps the upload request busy while the image is generated. For slower conversions, queued jobs move that work out of the request. If your configuration disables queuing conversions by default, queued() lets you queue a specific conversion.

Queued conversions run after the database transaction commits by default. This gives the worker a committed media record to use. The queue_conversions_after_database_commit configuration setting controls that behavior.

When supported, deferred() schedules a conversion to run after Laravel sends the HTTP response. The conversion still runs in the same PHP process, so a slow image can keep that worker occupied. Choose a queue for conversions that need separate background capacity. The official conversion documentation describes these execution options and their configuration.

Add responsive image sizes

A fixed conversion gives the browser one generated size. Responsive images provide multiple sizes so the browser can select an image suited to the displayed space. Add withResponsiveImages() to a conversion:

$this->addMediaConversion('responsive')
    ->width(1200)
    ->withResponsiveImages();

Media Library generates responsive variants and can provide markup with a srcset attribute, which lists image files the browser can choose from. It also creates a small base64 SVG placeholder for progressive loading. In a Blade view, output the Media object to use the package’s responsive-image markup:

{{ $media }}

Follow the responsive images setup when you want the package to generate and display those variants.

Use model data carefully

By default, Media Library runs conversion definitions without loading a specific model instance. If a conversion needs a model property, set $registerMediaConversionsUsingModelInstance = true on the model. This makes the model instance available to the conversion method. Media Library notes a performance cost because it queries each model.

Start with a fixed conversion definition when image dimensions and transformations do not depend on individual model records. Use instance-based definitions only when the conversion needs record-specific data.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *