Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Medialibrary Laravel Package

spatie/laravel-medialibrary

Attach and manage files on Eloquent models with an easy API. Handle uploads, store media on any Laravel filesystem (local, S3, etc.), organize collections, and generate image/PDF conversions and manipulations with built-in support for responsive images.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-medialibrary
    

    Publish the config (optional but recommended for customization):

    php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider"
    
  2. Model Setup: Use the HasMedia trait and RegistersMediaConversions trait (if using conversions):

    use Spatie\MediaLibrary\HasMedia;
    use Spatie\MediaLibrary\InteractsWithMedia;
    use Spatie\MediaLibrary\RegistersMediaConversions;
    
    class Post extends Model
    {
        use HasMedia, InteractsWithMedia, RegistersMediaConversions;
    
        // ...
    }
    
  3. First Upload:

    $post = Post::find(1);
    $post->addMedia($request->file('image'))->toMediaCollection('images');
    

Key First Use Cases

  • Basic Upload: Attach files to models using addMedia().
  • Retrieval: Access media via getFirstMedia() or collections with getMedia().
  • Deletion: Remove media with deleteMedia() or clear collections with clearMediaCollection().

Implementation Patterns

Core Workflows

  1. Media Collections:

    • Define collections in config/medialibrary.php or dynamically:
      $post->addMedia($file)->toMediaCollection('featured_images');
      
    • Access collections:
      $post->getMedia('images'); // Returns a Media collection
      
  2. Conversions:

    • Register conversions in registerMediaConversions():
      public function registerMediaConversions(Media $media = null): void
      {
          $this->addMediaConversion('thumb')
                ->width(100)
                ->height(100);
      }
      
    • Use conversions:
      $post->getFirstMedia('images')->getUrl('thumb');
      
  3. Custom Paths:

    • Override default paths via PathGenerator:
      $post->addMedia($file)
            ->usingFileName('custom_' . $file->getClientOriginalName())
            ->toMediaCollection('custom_collection');
      
  4. Temporary URLs:

    • Generate signed URLs for private files:
      $post->getFirstMedia('images')->getTemporaryUrl(60); // 60 seconds expiry
      

Integration Tips

  • Validation: Use Laravel’s validation rules to ensure files meet requirements before upload.
  • Events: Listen to MediaWasAdded, MediaWasDeleted, etc., for post-processing:
    event(new MediaWasAdded($post, $media));
    
  • API Responses: Use toResponse() for API-friendly media URLs:
    return $post->getFirstMedia('images')->toResponse();
    
  • Batch Operations: Leverage collections for bulk actions:
    $post->getMedia('images')->each(function ($media) {
        $media->regenerateConversions();
    });
    

Gotchas and Tips

Common Pitfalls

  1. Filesystem Configuration:

    • Ensure your filesystems.php is properly configured for the disk you’re using (e.g., s3, local).
    • Gotcha: S3 paths may double-encode URLs. Use encodePercentSigns: false in config for S3.
  2. Media Collection Naming:

    • Collection names must be strings and cannot contain spaces or special characters.
    • Tip: Use snake_case for consistency.
  3. Conversions:

    • Gotcha: Conversions are generated on-demand. Regenerate them explicitly if needed:
      $media->regenerateConversions();
      
    • Tip: Use deferred() for lazy conversion generation (v11.22.0+):
      $this->addMediaConversion('thumb')->deferred();
      
  4. Orphaned Files:

    • Run php artisan media:clean to remove files not referenced by any model.
    • Tip: For large projects, use --hash-lookup (v11.17.8+) for faster cleanup.
  5. Custom Path Generators:

    • Gotcha: If using custom paths, ensure PathGenerator implements Spatie\MediaLibrary\PathGenerators\PathGenerator.
    • Tip: Override getPathFor() in your model’s PathGenerator:
      public function getPathFor(Media $media): string
      {
          return 'custom/' . $media->model->id . '/' . $media->file_name;
      }
      
  6. Temporary URLs:

    • Gotcha: Temporary URLs expire. Cache them if needed or use getAvailableTemporaryUrl() (v11.20.0+) for pre-signed URLs.
    • Tip: Set a default expiry in config/medialibrary.php:
      'temporary_url_expiration' => 3600, // 1 hour
      
  7. Image Drivers:

    • Gotcha: GD, Imagick, and VIPS (v11.18.0+) are supported. Ensure your server has the correct extensions installed.
    • Tip: For Alpine Linux, install dependencies explicitly:
      apk add --no-cache graphicsmagick
      

Debugging Tips

  • Log Media Operations: Use MediaWasAdded/MediaWasDeleted events to log actions:
    MediaWasAdded::dispatch($model, $media);
    
  • Check Disk Space: Verify your filesystem has sufficient space for uploads.
  • Validate File Paths: Ensure paths in config/medialibrary.php are correct and writable:
    'disk' => 'public',
    'models' => [
        'post' => [
            'path' => 'posts/{id}',
            'conversions' => 'conversions',
        ],
    ],
    
  • Conversion Errors: If conversions fail, check:
    • File permissions on the disk.
    • Installed image libraries (GD/Imagick).
    • File formats (e.g., PDFs require spatie/pdf-to-image).

Extension Points

  1. Custom Media Models:

    • Extend Spatie\MediaLibrary\Models\Media to add custom fields:
      class CustomMedia extends Media
      {
          protected $casts = [
              'custom_field' => 'string',
          ];
      }
      
    • Update config/medialibrary.php to use your model:
      'models' => [
          'post' => [
              'model' => CustomMedia::class,
          ],
      ],
      
  2. Custom Conversions:

    • Create a MediaConversion class:
      class CustomConversion extends MediaConversion
      {
          public function manipulate($convert)
          {
              // Custom logic (e.g., FFmpeg for videos)
          }
      }
      
    • Register it in registerMediaConversions():
      $this->addMediaConversion('custom')
            ->usingCustomManipulation(CustomConversion::class);
      
  3. Custom Storage:

    • Use Laravel’s filesystem drivers (e.g., s3, ftp) by specifying the disk in toMediaCollection():
      $post->addMedia($file)->toMediaCollection('downloads', 's3');
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai