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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-media

Extremely powerful media library for Laravel 🖼️

Latest Version on Packagist Total Downloads Tests Laravel Pint PHPStan

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:

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

  1. Requirements

  2. Installation

  3. Basic Usage

    • Define Media Collection
    • Define Media Conversions
    • Adding Media
    • Retreiving Media
    • Media properties
    • Accessing Media Conversions
    • Blade components
  4. Advanced Usage

    • Transforming a file before storing it
    • Async vs Sync conversions
    • Delayed conversions
    • onAdded MediaCollection Callback
    • onCompleted MediaConversionDefinition Callback
    • Regenerating Child Conversions When a Parent Runs
    • Custom conversions
    • Manually generate conversions
    • Format Media Url
  5. Conversions Presets

    • Image Placeholder
    • Video Streaming (HLS)
    • Video Sprite Sheets
  6. Customization

    • Custom Media Model
  7. Troubleshooting
    • Ghostscript and Imagick Issues

Requirements

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:

Adding Media

Add media to your model, using the addMedia method, from various sources:

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:

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:

By combining these parameters, you can retrieve formatted URLs like this:

This package comes with 3 formatters out of the box:

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 Blade component, you can directly specify the placeholder conversion name:

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:

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

License

The MIT License (MIT). Please see the License File for more information.


All versions of laravel-media with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
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
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package finller/laravel-media contains the following files

Loading the files please wait ...