Kritim Yantra
Apr 16, 2025
In this blog post, we'll explore how to integrate and use the Spatie Laravel-Medialibrary package in Laravel 12 to manage file uploads, associate them with Eloquent models, and perform advanced media operations like conversions and responsive images.
The Spatie Laravel-Medialibrary is a powerful package that simplifies file management in Laravel applications. It allows you to:
avatars
, documents
).If you don’t have Laravel 12 installed, create a new project:
composer create-project laravel/laravel laravel-media-app
cd laravel-media-app
Install the package via Composer:
composer require spatie/laravel-medialibrary
Publish the migration and configuration file:
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"
php artisan migrate
Publish the config file (optional):
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="config"
Ensure your config/filesystems.php
has a public
disk (for local storage):
'disks' => [
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
],
Create a symbolic link:
php artisan storage:link
Add the InteractsWithMedia
trait to your model (e.g., User
or Post
):
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Database\Eloquent\Model;
class Post extends Model implements HasMedia
{
use InteractsWithMedia;
}
Upload and attach a file to a model:
$post = Post::find(1);
$post->addMedia($request->file('image'))->toMediaCollection('images');
This will:
storage/app/public
.media
table.Get the media URL:
$post->getFirstMediaUrl('images'); // Returns URL
$post->getFirstMediaPath('images'); // Returns storage path
You can define multiple collections (e.g., images
, documents
):
public function registerMediaCollections(): void
{
$this->addMediaCollection('images')
->acceptsMimeTypes(['image/jpeg', 'image/png'])
->singleFile(); // Only allow one file
}
Usage:
$post->addMedia($file)->toMediaCollection('images');
Generate thumbnails and optimized images.
In your model:
use Spatie\MediaLibrary\MediaCollections\Models\Media;
public function registerMediaConversions(Media $media = null): void
{
$this->addMediaConversion('thumb')
->width(150)
->height(150)
->sharpen(10);
}
$post->getFirstMediaUrl('images', 'thumb'); // Returns thumbnail URL
Serve optimized images for different screen sizes:
$this->addMediaConversion('responsive')
->withResponsiveImages();
In Blade:
<img
src="{{ $post->getFirstMediaUrl('images') }}"
srcset="{{ $post->getFirstMedia('images')->getSrcset('responsive') }}"
sizes="(max-width: 768px) 100vw, 50vw"
/>
$post->addMedia($file)
->withCustomProperties(['author' => 'John Doe'])
->toMediaCollection('images');
media-library
disk to use S3.->nonQueued() // Default
->queued() // Process in queue
The Spatie Laravel-Medialibrary is an essential tool for handling file uploads in Laravel 12. It provides:
✅ Easy file association with models.
✅ Image optimizations & conversions.
✅ Responsive image support.
✅ Flexible storage options (local, S3).
Start using it today to simplify file management in your Laravel projects!
Happy coding! 🚀
Transform from beginner to Laravel expert with our personalized Coaching Class starting June 9, 2025. Limited enrollment ensures focused attention.
1-hour personalized coaching
Build portfolio applications
Industry-standard techniques
Interview prep & job guidance
Complete your application to secure your spot
Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google