Laravel Spatie Media Library: What It Is, How to Use It, and Why It Matters

Laravel Spatie Media Library: The Practical Guide (Setup, Buckets, Conversions & Manipulation)
Handling uploads in Laravel is easy with the default filesystem, but managing real media workflows—associating files to models, generating thumbnails, keeping collections organized, and updating images safely—often becomes repetitive and error-prone. That’s exactly where Spatie’s Laravel Media Library shines.
What is Spatie Laravel Media Library?
Laravel Media Library is a package by Spatie that lets you associate files with Eloquent models (e.g., users, products, posts) and manage them as “media” rather than raw paths. It supports:
- Attaching files to models via a clean API
- Organizing files into collections (e.g.,
avatar,gallery,documents) - Generating media conversions (thumbnails, webp, resized variants)
- Storing media on any filesystem disk (local, S3, etc.)
- Optional image manipulation using Spatie’s image tools
Official links:
- Spatie Media Library documentation: https://spatie.be/docs/laravel-medialibrary
- GitHub repository: https://github.com/spatie/laravel-medialibrary
- Spatie (publisher): https://spatie.be/
Why use a media library instead of Laravel’s default Storage?
Laravel’s filesystem (Storage) is excellent for reading/writing files, but it’s intentionally low-level. You typically end up building your own “media layer” to answer questions like:
- Which files belong to which model record?
- How do I store multiple images per product and keep them ordered?
- How do I generate and retrieve thumbnails reliably?
- How do I replace an image and clean up the old one?
- How do I keep consistent naming, directories, and metadata?
Media Library is better when you want a structured, maintainable approach:
- Model association: Files are first-class records in the DB (
mediatable) linked polymorphically to your models. - Collections: Separate “avatar” from “gallery” without inventing folder conventions.
- Conversions: Generate thumbnails/variants once, retrieve them by name.
- Consistency: Standardized APIs reduce custom code and edge cases.
- Cleanup & replacement: Removing media can automatically remove files; replacing media is straightforward.
- Metadata: Store custom properties, responsive images, and more.
In short: Storage is the filesystem tool; Media Library is the media management system built on top of it.
How to install and set up Spatie Media Library
Install the package:
composer require spatie/laravel-medialibraryPublish and run migrations (the package stores media records in a database table):
php artisan vendor:publish --provider="Spatie\\MediaLibrary\\MediaLibraryServiceProvider" --tag="medialibrary-migrations" php artisan migratePublish config (optional) if you want to tweak defaults:
php artisan vendor:publish --provider="Spatie\\MediaLibrary\\MediaLibraryServiceProvider" --tag="medialibrary-config"Update your model to become “media-aware”:
use Illuminate\Database\Eloquent\Model; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; class User extends Model implements HasMedia { use InteractsWithMedia; }
How to use it: attaching media to a model
The most common workflow is: receive an uploaded file, attach it to a model, assign it to a collection.
Example: upload an avatar
public function updateAvatar(Request $request)
{
$request->validate([
'avatar' => ['required', 'image', 'max:2048'],
]);
$user = $request->user();
// Optionally keep only one avatar by clearing the collection first
$user->clearMediaCollection('avatar');
$user
->addMediaFromRequest('avatar')
->toMediaCollection('avatar');
return back();
}Retrieving URLs
$avatarUrl = $user->getFirstMediaUrl('avatar');
$avatar = $user->getFirstMedia('avatar');Multiple files: gallery
foreach ($request->file('images', []) as $image) {
$product->addMedia($image)->toMediaCollection('gallery');
}Connecting Media Library to storage buckets (S3 and other disks)
Media Library stores files on Laravel filesystem disks, which means it can work with local storage, Amazon S3, DigitalOcean Spaces, Google Cloud Storage, and more—anything supported by Laravel’s filesystem.
1) Configure your disk (example: S3)
In config/filesystems.php:
'disks' => [
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
],2) Tell Media Library which disk to use
You can set a default disk in the Media Library config, or choose a disk per upload:
$user
->addMediaFromRequest('avatar')
->toMediaCollection('avatar', 's3');This approach is extremely useful when you want local storage in development but S3 in production, or when different collections should go to different buckets/disks (e.g., private documents vs public images).
Media conversions: thumbnails, resized images, WebP, and more
Media conversions are named transformations of an uploaded file. For images, this typically means generating thumbnails and optimized sizes. Instead of resizing images manually and managing filenames yourself, you define conversions once and let the library generate them.
Define conversions on the model
use Spatie\MediaLibrary\MediaCollections\Models\Media;
class Product extends Model implements \Spatie\MediaLibrary\HasMedia
{
use \Spatie\MediaLibrary\InteractsWithMedia;
public function registerMediaConversions(?Media $media = null): void
{
$this
->addMediaConversion('thumb')
->width(300)
->height(300);
$this
->addMediaConversion('web')
->width(1200)
->format('webp')
->quality(80);
}
}Retrieve a conversion URL
$url = $product->getFirstMediaUrl('gallery', 'thumb');
$webUrl = $product->getFirstMediaUrl('gallery', 'web');Conversions help you deliver the right size to the right context (admin tables, product pages, listings) without repeatedly processing images at runtime.
Image manipulation and updating images through the Media Library
Media Library integrates with Spatie’s image manipulation pipeline for conversions, so you can crop, resize, change format, adjust quality, and more as part of your conversions.
Common manipulations
Within registerMediaConversions(), you can do things like:
- Resize/crop to consistent dimensions for UI
- Convert to modern formats like WebP
- Adjust quality to reduce file size
Replacing/updating an image (safe and clean)
A frequent requirement is “update the avatar” or “replace the product’s main image.” With Media Library, the clean pattern is:
- Clear the collection (or delete a specific media item)
- Add the new file to the same collection
- Conversions are regenerated for the new file
public function replaceMainImage(Request $request, Product $product)
{
$request->validate([
'image' => ['required', 'image', 'max:5120'],
]);
// Keep exactly one image in this collection
$product->clearMediaCollection('main');
$product
->addMediaFromRequest('image')
->toMediaCollection('main');
return back();
}This is much less error-prone than manually deleting old files, updating database columns with new paths, and ensuring thumbnails are consistent.
Editing an existing media item vs. re-uploading
In many applications, the simplest and most reliable “update” is to replace the media item (delete old, add new) so the original and conversions stay consistent. For advanced use cases (custom properties, ordering, metadata), you can update the media record itself, but image content changes are typically handled by replacement plus conversions.
Best practices (quick checklist)
- Use collections intentionally:
avatar,main,gallery,documents. - Generate conversions for UI needs: thumbnails for tables, medium for cards, large/webp for pages.
- Store public vs private separately: consider separate disks or visibility rules for sensitive files.
- Replace single-image collections:
clearMediaCollection()before adding new media. - Use S3 (or similar) in production: scalable storage, CDN-friendly delivery.
Conclusion
Spatie’s Laravel Media Library gives you a robust, model-centric way to manage uploads: clean associations, collections, conversions, and bucket storage support—without reinventing a media management layer on top of Laravel Storage.
If your application handles user avatars, product images, galleries, or documents, adopting Media Library usually pays for itself quickly in maintainability and consistency.
Explore the official resources: