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

Media Manager Laravel Package

canaltp/media-manager

Laravel media manager package for organizing uploaded files with a simple, developer-friendly API. Helps store, retrieve, and manage media assets (images, documents, etc.) in your app, with streamlined integration into common Laravel workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require canaltp/media-manager
    

    Publish the package assets and configuration:

    php artisan vendor:publish --provider="CanalTP\MediaManager\Component\MediaManagerServiceProvider" --tag="config"
    php artisan vendor:publish --provider="CanalTP\MediaManager\Component\MediaManagerServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="CanalTP\MediaManager\Component\MediaManagerServiceProvider" --tag="public"
    

    Run migrations:

    php artisan migrate
    
  2. Configuration Review config/media-manager.php to set:

    • Default storage disk (default_disk)
    • Allowed MIME types (allowed_mime_types)
    • File size limits (max_file_size)
    • Custom paths for uploads (upload_paths)
  3. First Use Case: Uploading a File

    use CanalTP\MediaManager\Component\Contracts\MediaManagerContract;
    use Illuminate\Support\Facades\Storage;
    
    $mediaManager = app(MediaManagerContract::class);
    
    $file = request()->file('file');
    $media = $mediaManager->upload($file, [
        'disk' => 'public',
        'path' => 'uploads',
        'name' => 'custom_filename.jpg',
    ]);
    
    // $media now contains metadata like URL, path, size, etc.
    

Implementation Patterns

Core Workflows

  1. File Uploads

    • Basic Upload:
      $media = $mediaManager->upload($file, ['disk' => 'public']);
      
    • Custom Paths:
      $media = $mediaManager->upload($file, [
          'path' => 'custom/folder',
          'name' => 'user_' . auth()->id() . '_' . time() . '.jpg'
      ]);
      
    • Validation: Use Laravel's built-in validation before passing to MediaManager:
      $request->validate([
          'file' => 'required|mimes:' . implode(',', config('media-manager.allowed_mime_types')),
          'file.*' => 'max:' . config('media-manager.max_file_size')
      ]);
      
  2. File Management

    • Retrieve Media:
      $media = $mediaManager->get('path/to/file.jpg');
      
    • Delete Media:
      $mediaManager->delete($media->path);
      
    • List Media:
      $mediaList = $mediaManager->list('uploads');
      
  3. Integration with Eloquent

    • Attach Media to Models: Use Laravel's morphToMany or a custom trait:
      // Example trait
      use CanalTP\MediaManager\Component\Traits\HasMedia;
      
      class Post extends Model
      {
          use HasMedia;
      }
      
      Then attach media:
      $post->addMedia($media)->toMedia('images');
      
  4. Thumbnails and Processing

    • Use Laravel's spatie/laravel-medialibrary or intervention/image alongside:
      $mediaManager->process($media->path, function ($image) {
          $image->resize(300, 200);
          return $image;
      });
      

Advanced Patterns

  1. Custom Storage Disks Configure additional disks in config/filesystems.php and reference them:

    $media = $mediaManager->upload($file, ['disk' => 's3']);
    
  2. Event Handling Listen for media events (e.g., MediaUploaded):

    // In EventServiceProvider
    protected $listen = [
        'CanalTP\MediaManager\Component\Events\MediaUploaded' => [
            'App\Listeners\LogMediaUpload',
        ],
    ];
    
  3. API Responses Serialize media for APIs:

    return response()->json([
        'media' => $media->toArray(),
        'url' => $media->getUrl(),
    ]);
    
  4. Batch Operations Process multiple files:

    foreach ($request->file('files') as $file) {
        $mediaManager->upload($file, ['path' => 'batch_uploads']);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Permission Issues

    • Ensure the storage disk has proper permissions:
      chmod -R 775 storage/app/public
      
    • For S3, verify IAM roles and bucket policies.
  2. MIME Type Restrictions

    • Double-check allowed_mime_types in config. Use fileinfo for dynamic checks:
      $mime = mime_content_type($file->getPathname());
      if (!in_array($mime, config('media-manager.allowed_mime_types'))) {
          throw new \Exception('Invalid file type');
      }
      
  3. File Naming Collisions

    • Use Str::uuid() or timestamps to avoid overwrites:
      $name = Str::uuid() . '.' . $file->getClientOriginalExtension();
      
  4. Missing Migrations

    • If media table is missing, republish migrations:
      php artisan vendor:publish --tag="migrations" --force
      

Debugging Tips

  1. Log Uploads Enable debug mode in config/media-manager.php:

    'debug' => env('MEDIA_MANAGER_DEBUG', false),
    

    Check logs for errors during uploads.

  2. Storage Disk Verification Test disk connectivity:

    Storage::disk('public')->put('test.txt', 'test');
    
  3. Event Debugging Use Laravel's events.log or dd() in event listeners:

    public function handle(MediaUploaded $event) {
        dd($event->media);
    }
    

Extension Points

  1. Custom Media Models Extend the Media model:

    class CustomMedia extends \CanalTP\MediaManager\Component\Models\Media
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    

    Update the config to use your model.

  2. Add Metadata Extend the upload method to include custom metadata:

    $media = $mediaManager->upload($file, [
        'metadata' => [
            'author_id' => auth()->id(),
            'tags' => ['image', 'profile'],
        ],
    ]);
    
  3. Custom Storage Drivers Implement CanalTP\MediaManager\Component\Contracts\StorageDriver for new backends (e.g., FTP, Dropbox).

  4. Validation Rules Create custom rules for file validation:

    use CanalTP\MediaManager\Component\Rules\ValidMediaType;
    
    $request->validate([
        'file' => ['required', new ValidMediaType],
    ]);
    

Performance Tips

  1. Chunked Uploads For large files, use client-side chunking (e.g., Dropzone.js) and implement server-side reassembly.

  2. Queue Uploads Offload processing to queues:

    UploadMediaJob::dispatch($file, $options)->onQueue('media');
    
  3. Optimize Thumbnails Cache thumbnails to avoid reprocessing:

    if (!$media->thumbnailExists()) {
        $media->generateThumbnail();
    }
    
  4. Lazy Loading Use with() to eager-load media relationships:

    $post->load('media');
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
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