spatie/laravel-medialibrary
Attach files to Eloquent models with an easy API. Upload from disk or request, store media across multiple filesystems (local/S3), and generate image/PDF conversions and manipulations using Laravel’s Filesystem.
Begin by installing the package via Composer (composer require spatie/laravel-medialibrary) and publishing its config (php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="medialibrary-config"). Next, run the migration (php artisan migrate) to create the media table. Then, attach the HasMedia trait and InteractsWithMedia trait to your Eloquent model (e.g., Product), and define a media collection using addMediaCollection() or registerMediaCollections() in the model’s boot method. Finally, upload a file using $model->addMedia($path)->toMediaCollection('images').
'featured', 'thumbnails') to logically group media for different use cases (e.g., product images vs. logos).registerMediaConversions() to generate optimized thumbnails (e.g., addMediaConversion('thumb')->width(300)->height(300)). Use queued conversions (->withResponsiveImages()->useQueue() for performance).addMedia()->withCustomProperties(['alt' => 'Image alt text']) or prohibitEmptyString() to enforce required fields.getFirstMediaUrl('collection'), getMedia('collection'), or getFirstMediaUrl('collection', 'conversion') in Blade for templating (e.g., <img src="{{ $product->getFirstMediaUrl('images', 'thumb') }}">).toResponse() for direct downloads or generate signed URLs for temporary access via url() method.media_disk in config/media-library.php matches your config/filesystems.php disk (e.g., public, s3). For local storage, run php artisan storage:link to expose files under storage/app/public.public disk, conversions won’t be accessible unless storage/app/public is symlinked to public/storage. Double-check the symlink is valid after deployment.media table’s model_id column is uuid-compatible (e.g., char(36)). Adjust the migration or use $model->registerMediaCollections() with usingUuids().memory_limit and consider chunked uploads or using a job to process media (e.g., ->toMediaCollection('videos')->onQueue('media')).->maxFiles(1) in your collection registration or check ->hasMedia('collection') before adding to avoid accidental duplication.MediaGenerator or use laravel-medialibrary’s test helpers (e.g., expectsOutput, assertDatabaseCount('media', ...)) when writing feature tests for media actions.How can I help you explore Laravel packages today?