Managing images, documents, videos, and other uploaded files is a common requirement in Laravel applications. While Laravel provides excellent support for file uploads and storage, applications with more advanced media-management requirements often need additional functionality.
This is where Spatie Laravel Media Library can help. The package provides a convenient way to associate files with Eloquent models, generate image conversions, manage collections, work with responsive images, and store media using Laravel's filesystem configuration.
In this guide, we'll explore what Spatie Media Library is, how to install it, and how to use its most useful features in a Laravel application.
What Is Spatie Laravel Media Library?
Spatie Laravel Media Library is a Laravel package developed by Spatie that allows you to associate uploaded media files with Eloquent models.
For example, imagine you have a Product model. Instead of manually managing image paths, filenames, directories, and database records, you can use Media Library to attach images directly to the product.
A product could have:
- A main product image
- Multiple gallery images
- Product documentation
- Thumbnail versions
- Optimized image conversions
The package handles much of the underlying media-management logic for you.
Why Use Spatie Media Library?
A simple file upload system can work well for small applications. However, as your application grows, media management can become more complicated.
Spatie Media Library provides features such as:
- Attaching media to Eloquent models
- Media collections
- Image conversions
- Automatic file organization
- Multiple filesystem disks
- Responsive images
- Media metadata
- Custom media models
- Temporary URLs
- File manipulation
- Collection-specific upload rules
This can significantly reduce the amount of custom code required in your Laravel application.
Installing Spatie Media Library
First, install the package using Composer:
composer require spatie/laravel-medialibrary
After installation, publish the package configuration and migrations:
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="media-library-migrations" php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="media-library-config"
Then run your migrations:
php artisan migrate
The package uses a media database table to store information about uploaded files and their relationships with your application models.
Preparing an Eloquent Model
To make a model capable of storing media, implement the HasMedia interface and use the InteractsWithMedia trait.
For example:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Product extends Model implements HasMedia
{
use InteractsWithMedia;
}
Your Product model can now have media attached to it.
Uploading Media
Suppose you have uploaded an image using a Laravel form. You can attach it to a product like this:
$product
->addMedia($request->file('image'))
->toMediaCollection();
The file will be registered in the Media Library and associated with the product.
You can also specify a collection:
$product
->addMedia($request->file('image'))
->toMediaCollection('product-images');
Using named collections is especially useful when a model contains different types of media.
For example:
- product-images
- product-documents
- gallery
- avatars
Retrieving Media
You can retrieve all media associated with a model:
$media = $product->getMedia();
To retrieve media from a specific collection:
$images = $product->getMedia('product-images');
You can also retrieve the first item from a collection:
$image = $product->getFirstMedia('product-images');
For a convenient URL, you can use:
$url = $product->getFirstMediaUrl('product-images');
This is useful when displaying images in Blade templates.
<img src="{{ $product->getFirstMediaUrl('product-images') }}" alt="{{ $product->name }}">
Using Media Collections
Media collections help organize files attached to a model.
You can define collections inside your model:
public function registerMediaCollections(): void
{
$this
->addMediaCollection('product-images')
->useDisk('public');
}
You can then upload files specifically to that collection:
$product
->addMedia($request->file('image'))
->toMediaCollection('product-images');
Collections become particularly useful in larger applications where a single model may contain several different types of files.
Image Conversions
One of the most useful features of Spatie Media Library is image conversion.
Instead of uploading an image and manually creating thumbnails, you can define conversions.
For example:
public function registerMediaConversions(?Media $media = null): void
{
$this
->addMediaConversion('thumbnail')
->width(300)
->height(300);
}
Now Media Library can generate a thumbnail version of the uploaded image.
You can retrieve the converted image URL with:
$product->getFirstMediaUrl('product-images', 'thumbnail');
In Blade:
<img
src="{{ $product->getFirstMediaUrl('product-images', 'thumbnail') }}"
alt="{{ $product->name }}"
>
This is useful for product catalogs, profile pictures, blog images, galleries, and other applications where the same original image needs to be displayed at different sizes.
Working With Multiple Storage Disks
Laravel supports multiple filesystem disks, and Spatie Media Library can work with them.
For example, you may want your public images stored on one disk while private documents are stored on another.
A collection can specify a disk:
$this
->addMediaCollection('documents')
->useDisk('private');
This makes it easier to separate public and private files within your application.
Replacing Existing Media
You can replace an existing file by adding a new file to the appropriate collection.
For example:
$product
->addMedia($request->file('image'))
->toMediaCollection('product-images');
Depending on how the collection is configured, you can also restrict a collection to a single file.
For example:
$this
->addMediaCollection('cover-image')
->singleFile();
This is useful for models that should have only one profile image, logo, cover image, or similar asset.
Deleting Media
You can remove individual media items when necessary.
For example:
$media = $product->getFirstMedia('product-images');
$media?->delete();
You can also clear an entire collection:
$product->clearMediaCollection('product-images');
This makes cleanup much easier than manually tracking file paths and deleting files from storage.
Useful Use Cases
Spatie Media Library can be useful in many types of Laravel applications.
E-commerce Applications
Products often need multiple images, thumbnails, downloadable manuals, and other media.
Blogging Platforms
Blog posts can have featured images, inline images, author avatars, and other assets.
User Profiles
Users can have profile pictures, cover photos, identification documents, or other files.
Real Estate Applications
Property listings can contain large galleries of images, floor plans, videos, and documents.
Document Management Systems
Documents can be attached to users, companies, projects, or other Eloquent models.
Best Practices
When using Spatie Media Library in production, a few practices can make your implementation easier to maintain.
Use Meaningful Collections
Instead of placing everything into the default collection, create descriptive collections such as:
profile gallery documents featured-image attachments
This makes your application easier to understand.
Validate Uploads
Always validate uploaded files before sending them to the media library.
For example:
$request->validate([
'image' => [
'required',
'image',
'max:5120',
],
]);
Validation helps prevent invalid or unnecessarily large files from being uploaded.
Use Image Conversions
If users upload large images, avoid serving the original file everywhere.
Generate appropriately sized conversions for:
- Thumbnails
- Cards
- Lists
- Detail pages
- Mobile layouts
This can reduce bandwidth usage and improve page performance.
Choose Storage Carefully
For applications with significant media requirements, consider whether local storage or cloud object storage is appropriate.
Laravel's filesystem abstraction makes it possible to configure different storage providers while keeping much of your application code relatively consistent.
Spatie Media Library vs. Manual File Management
With manual file management, you may need to handle:
- File validation
- File naming
- Directory organization
- Database records
- File deletion
- Image resizing
- Multiple versions
- Storage disks
- URL generation
Spatie Media Library provides an abstraction around many of these tasks.
This doesn't mean every Laravel project needs the package. For a very small application with a handful of uploads, Laravel's built-in filesystem features may be enough.
However, when media becomes an important part of your application's data model, Media Library can save considerable development time.
Conclusion
Spatie Laravel Media Library is a powerful solution for applications that need structured and flexible media management.
It makes it easier to associate files with Eloquent models, organize files into collections, generate image conversions, work with different storage disks, and retrieve media URLs.
If your Laravel application contains products, user profiles, blog posts, galleries, documents, or other media-heavy features, Spatie Media Library is worth considering.
The key is to design your media collections carefully, validate uploads, use appropriate image conversions, and choose a storage strategy that fits your application's requirements.
With these practices in place, you can build a cleaner and more maintainable media-management system without reinventing file-handling functionality from scratch.