Download the PHP package finller/laravel-media without Composer
On this page you can find all versions of the php package finller/laravel-media. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download finller/laravel-media
More information about finller/laravel-media
Files in finller/laravel-media
Package laravel-media
Short Description A flexible media library for Laravel
License MIT
Homepage https://github.com/ElegantEngineeringTech/laravel-media
Informations about the package laravel-media
Extremely powerful media library for Laravel 🖼️
This package offers an extremely flexible media library, enabling you to store any type of file along with their conversions.
It provides advanced features such as:
- 🌐 Supports any filesystem solutions (local or cloud), such as S3, R2, Bunny.net, DO...
- ⚡ Supports any file conversion solutions (local or cloud), such as ffmpeg, Transloadit, Cloudflare, Coconut, and others.
- 🔄 Advanced nested media conversions
- 🚀 Rich metadata automatically extracted
- 🛠️ Highly flexible and customizable
I developed this package with the highest degree of flexibility possible and I have been using it in production for nearly two years, handling terabytes of files monthly.
Table of Contents
-
Requirements
-
Installation
-
Basic Usage
- Define Media Collection
- Define Media Conversions
- Adding Media
- Retreiving Media
- Media properties
- Accessing Media Conversions
- Blade components
-
Advanced Usage
- Transforming a file before storing it
- Async vs Sync conversions
- Delayed conversions
onAddedMediaCollection CallbackonCompletedMediaConversionDefinition Callback- Regenerating Child Conversions When a Parent Runs
- Custom conversions
- Manually generate conversions
- Format Media Url
-
Conversions Presets
- Image Placeholder
- Video Streaming (HLS)
- Video Sprite Sheets
-
Customization
- Custom Media Model
- Troubleshooting
- Ghostscript and Imagick Issues
Requirements
- PHP 8.1+
- Laravel 11.0+
spatie/imagefor image conversionsspatie/pdf-to-imagefor PDF to image conversionsffmpegfor video/audio processing
Installation
You can install the package via composer:
You have to publish and run the migrations with:
You can publish the config file with:
This is the contents of the published config file:
Media and conversion records are deleted immediately; their files are deleted by DeleteMediaFileJob after the surrounding database transaction commits. With an asynchronous queue connection, run a worker for the configured queue to process cleanup. Failed file deletions throw an exception so the queue can retry them according to your worker settings.
When upgrading from delete_media_with_model_job, replace that config key with delete_media_file_job. Custom deletion jobs now receive string $disk and string $path instead of a Media model; extend DeleteMediaFileJob to retain after-commit cleanup and failure handling.
Optionally, you can publish the views using
Basic Usage
Defining Media Collections
Media Collections define how media are stored, transformed, and processed for a specific model. They provide granular control over file handling, accepted types, and transformations.
To associate a media collection with a Model, start by adding the InteractWithMedia interface and the HasMedia trait.
Next, define your collections in the registerMediaCollections method, as shown below:
Defining Media Conversions
Media conversions create different variants of your media files. For example, a 720p version of a 1440p video or a WebP or PNG version of an image are common types of media conversions. Interestingly, a media conversion can also have its own additional conversions.
This package provides common converter to simplify your work:
MediaImageConverter: This converter optimizes, resizes, or converts any image usingspatie/image.MediaMp4Converter: This conversion optimizes, resizes, or converts any video or gif to mp4 video usingffmpeg.MediaWebmConverter: This conversion optimizes, resizes, or converts any video or gif to webm video usingffmpeg.MediaAv1Converter: This conversion optimizes, resizes, or converts any video or gif to AV1 video (in an mp4 or webm container) usingffmpeg.MediaHlsConverter: This conversion encodes any video into an adaptive HLS stream with several resolutions usingffmpeg. See Video Streaming (HLS).MediaWavConverter: This conversion optimizes, resizes, converts or extract any audio in wav format usingffmpeg.MediaMp3Converter: This conversion optimizes, resizes, converts or extract any audio in mp3 format usingffmpeg.MediaOpusConverter: This conversion optimizes, resizes, converts or extract any audio in opus format usingffmpeg.MediaFrameConverter: This conversion extracts a frame from a video usingffmpeg.MediaThumbnailConverter: This conversion smartly extracts the best thumbnail from a video usingffmpeg.MediaSpritesheetConverter: This conversion tiles frames of a video or gif into sprite sheets, with a WebVTT file for timeline previews, usingffmpeg. See Video Sprite Sheets.MediaPdfToImageConverter: This conversion extracts an image from the PDF usingspatie/pdf-to-image.
Adding Media
Add media to your model, using the addMedia method, from various sources:
- an url
- a resource or stream
- a
\Illuminate\Http\UploadedFileinstance - a
\Illuminate\Http\Fileinstance
From a Controller
From a Livewire Component
From an Url
Retreiving Media
Retrieve media from your model:
Media properties
Each media item provides rich metadata automatically:
You can use dot notation to access either the root properties or a specific conversion:
Access Media Conversions
To directly access conversions, use:
Blade components
The package also provides blade components.
Advanced Usage
Transforming a file before storing it
You can define a transformation step that runs before a file is stored by using the transform method on a media collection.
This is useful if you want to resize, optimize, or process an uploaded file before it gets saved to disk.
For example, the snippet below shows how you can resize and optimize an uploaded image before storing it:
Async vs. Sync Conversions
When adding new media, its conversions can be either dispatched asynchronously or generated synchronously.
You can configure the strategy in the conversion definition using the queued and queue parameters:
Synchronous conversions can be particularly useful in specific use cases, such as generating a poster immediately upon upload.
Delayed Conversions
There are scenarios where you might want to define conversions that should not be generated immediately. For instance, if a conversion is resource-intensive or not always required, you can defer its generation to a later time.
To achieve this, configure the conversion with the immediate parameter set to false. This allows you to generate the conversion manually when needed:
To generate the conversion later, you can use the following methods:
onAdded MediaCollection Callback
The onAdded callback allows you to define custom logic that will be executed whenever new media is added to your collection.
To use it, simply set the onAdded parameter when defining a MediaCollection. For example:
With this, you can easily hook into the media addition process and trigger actions like sending notifications, logging, or other custom behavior.
[!TIP] The same behavior can be achieved by listening to
Elegantly\Media\Events\MediaAddedEvent.
onCompleted MediaConversionDefinition Callback
The onCompleted callback allows you to define custom logic that will be executed whenever a new conversion is generated.
To use it, simply set the onCompleted parameter when defining a MediaConversionDefinition. For example:
This allows you to hook into the conversion process and execute additional logic, such as updating your UI or triggering other actions.
[!TIP] The same behavior can be achieved by listening to
Elegantly\Media\Events\MediaConversionAddedEvent.
Regenerating Child Conversions When a Parent Runs
In some cases, you may want all child conversions of a given conversion to be regenerated whenever the parent conversion is re-executed.
There are two ways to achieve this, depending on where you handle conversions:
From the conversion definition
You can hook into the onCompleted callback of a conversion definition and instruct Laravel to delete all child conversions when the parent finishes.
From addConversion
When adding a new conversion programmatically, you can explicitly tell it to remove children and regenerate them automatically:
Custom Conversions
Conversions can be anything: a variant of a file, a transcription of a video, a completely new file, or even just a string.
You can use built-in presets or define your own custom converter. To create a custom converter, start by creating a new class extending the MediaConverter class:
The convert method is where the logic for the conversion is implemented. It provides the following parameters:
$media: The Media model.$parent: The MediaConversion model, if the conversion is nested.$file: A local copy of the file associated with either$mediaor$parent.$filesystem: An instance of the local filesystem where the file copy is stored.$temporaryDirectory: An instance ofTemporaryDirectorywhere the file copy is temporarily stored.
You don’t need to worry about cleaning up the files, as the $temporaryDirectory will be deleted automatically when the process completes or fails.
To finalize the conversion, ensure you save it by calling $media->addConversion or $media->replaceConversion at the end of the handle method.
Manually Generate Conversions
You can manage your media conversions programmatically using the following methods:
Additionally, you can use an Artisan command to generate conversions with various options:
You can also use the following command to retry failed conversions:
To regenerate existing conversions, filtered by name, state and creation date (--with-force-children also re-generates their existing children):
This provides a convenient way to process conversions in bulk or automate them within your workflows.
Format Media URLs
Some cloud providers like Cloudflare, Bunny, or ImageKit allow you to create instant transformations of your images and videos using specially formatted URLs.
This package gives you a simple way to format your URLs so you can take advantage of these services.
When using the $media->getUrl() method, you can specify two parameters:
parameters: An array of valuesformatter: The class name of the formatter you want to use
By combining these parameters, you can retrieve formatted URLs like this:
This package comes with 3 formatters out of the box:
\Elegantly\Media\UrlFormatters\DefaultUrlFormatter\Elegantly\Media\UrlFormatters\CloudflareImageUrlFormatter\Elegantly\Media\UrlFormatters\CloudflareVideoUrlFormatter
Feel free to implement your own formatter by extending \Elegantly\Media\UrlFormatters\AbstractUrlFormatter.
Conversions Presets
Image Placeholder
When loading images on the web, it’s common to show a low-resolution blurred placeholder first, then swap it with the full-resolution image once it’s ready. This improves perceived performance, reduces layout shifts, and gives a polished feel to your UI.
This package includes a ready-to-use preset for generating these placeholders in Base64-encoded format. The placeholder is tiny in size, quick to load, and designed to be displayed while the actual image is being fetched.
Defining the Placeholder Conversion
To create a placeholder, simply define a media conversion using the MediaImagePlaceholderConverter:
Using the Placeholder in Your Views
If you’re using the built-in
This will automatically load the blurred placeholder as a background-image.
Retrieving the Base64 Value Directly
If you need to manually work with the placeholder (e.g., for API responses or inline styles), you can retrieve it like this:
Video Streaming (HLS)
HLS (HTTP Live Streaming) splits a video into short segments encoded at several resolutions. Players start quickly, then switch to the resolution the connection allows.
The MediaHlsConverter encodes a variant for each rendition the source fills, without upscaling, and writes the master playlist listing them with the attributes Apple devices require: the peak and average bandwidths, the codecs, the resolution and the frame rate.
Defining the HLS Conversion
| Parameter | Default | Description |
|---|---|---|
renditions |
null |
The sizes of the renditions to generate, among media.videos.hls.renditions. null generates all of them. |
startingRendition |
720 |
The size of the rendition players start with, listed first in the master playlist. |
segmentLength |
6 |
The duration of a segment, in seconds. |
fps |
null |
The maximum frame rate, never raising the frame rate of the source. |
crf, preset |
23, slow |
The quality targeted by x264, and its compression speed. |
playlist |
master.m3u8 |
The file name of the master playlist. |
Stored Files and Variants
The conversion file is the master playlist. The media playlists and segments of each variant are stored as additional files next to it, as the playlists reference them by their file name. The variants are saved in the conversion metadata, in the order of the master playlist:
Playing the Stream
Safari plays HLS natively. Other browsers play it through hls.js, which most video players are built on:
Video Sprite Sheets
A sprite sheet is a single image tiling many frames of a video in a grid. It powers the previews shown when hovering the timeline of a video player, or when scrubbing a video card with the mouse, with a single request.
The MediaSpritesheetConverter extracts frames at a regular interval, tiles them into one or several sheets, and writes the WebVTT file video players read timeline thumbnails from. Like an HLS playlist, the WebVTT file is the conversion file and references the sheets stored next to it.
Defining the Sprite Sheet Conversion
| Parameter | Default | Description |
|---|---|---|
filename |
The WebVTT file, also naming the sheets (sprites_0.jpg, sprites_1.jpg... for sprites.vtt). Use a .vtt extension. |
|
format |
jpg |
The image format of the sheets: jpg, webp or png. |
interval |
null |
The time between two frames in seconds. null spreads the frames evenly over the whole video. |
frames |
null |
The maximum number of frames, the interval being widened on long videos. Defaults to a single sheet (columns × rows) without interval, and to no limit otherwise. |
width, height |
160, null |
The maximum size of a frame, keeping the aspect ratio. Frames are never upscaled. |
columns, rows |
10, 10 |
The grid of a sheet, the following frames going to a new sheet. The grid shrinks when the frames don't fill a single sheet. |
Stored Files and Layout
Like an HLS playlist, the conversion file is the WebVTT file. The sheets are stored as additional files next to it, and the layout is saved in the conversion metadata:
Frame n shows the video at n × interval seconds. It is in the sheet floor(n / (columns × rows)), at x = (n % columns) × width and y = floor(n % (columns × rows) / columns) × height.
Timeline Previews in Video Players
Most video players (Vidstack, Video.js, Plyr, Media Chrome...) display timeline thumbnails from a WebVTT file. Each cue references its frame with a media fragment (e.g. sprites_0.jpg#xywh=160,0,160,90), relative to the WebVTT file, so give the player its URL:
Hover Previews
To scrub a video card with the mouse, the metadata is enough to display the right frame of a single sheet:
In JavaScript, the sheets can also be resolved from the URL of the WebVTT file: new URL(metadata.sheets[0], url).
Customization
Custom Media Model
You can define your own Media model to use with the library.
First, create your own model class:
Then, update the config file:
The library is typed with generics, so you can use your own Media model seamlessly:
Troubleshooting
Ghostscript and Imagick Issues
This package relies on the spatie/pdf-to-image library, which uses Ghostscript via Imagick to convert PDFs into images.
If you encounter errors while generating images from PDFs, such as:
attempt to perform an operation not allowed by the security policy 'PDF'Uncaught ImagickException: FailedToExecuteCommand 'gs'
these issues are likely related to the configuration of Ghostscript or Imagick on your system.
For detailed guidance on resolving these errors, refer to the spatie/pdf-to-image documentation on Ghostscript issues.
Testing
Changelog
Please see the CHANGELOG for more information on recent changes.
Contributing
Feel free to open an issue or a discussion.
Security Vulnerabilities
Please contact me to report security vulnerabilities.
Credits
- Quentin Gabriele
- All Contributors
License
The MIT License (MIT). Please see the License File for more information.
All versions of laravel-media with dependencies
illuminate/contracts Version ^11.0||^12.0||^13.0
maennchen/zipstream-php Version ^3.1
spatie/image Version ^3.0.0
spatie/laravel-package-tools Version ^1.14.0
spatie/pdf-to-image Version ^3.1
spatie/temporary-directory Version ^2.4
symfony/process Version ^6.4||^7.0||^8.0