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 Bundle Laravel Package

donjohn/media-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Run composer require donjohn/media-bundle in your Laravel project (note: this is a Symfony bundle, but can be adapted for Laravel via Bridge or manually). Publish the bundle’s assets/config with:

    php artisan vendor:publish --provider="Donjohn\MediaBundle\DonjohnMediaBundle"
    
  2. Define a Media Entity Extend Donjohn\MediaBundle\Model\Media in your app/Models directory:

    namespace App\Models;
    
    use Donjohn\MediaBundle\Model\Media as BaseMedia;
    use Illuminate\Database\Eloquent\Model;
    
    class Media extends BaseMedia
    {
        protected $table = 'media';
    }
    

    Run php artisan migrate (ensure donjohn_media migrations are included).

  3. Configure LiipImagine Add to config/imagine.php (or config/packages/liip_imagine.yaml if using Symfony):

    'filter_sets' => [
        'full' => ['quality' => 100],
        'thumbnail' => [
            'quality' => 75,
            'filters' => [
                'thumbnail' => ['size' => [120, 120], 'mode' => 'outbound'],
            ],
        ],
    ],
    
  4. First Upload Use the MediaManager service to upload files:

    use Donjohn\MediaBundle\Manager\MediaManager;
    
    $mediaManager = app(MediaManager::class);
    $media = $mediaManager->create([
        'name' => 'example.jpg',
        'path' => 'uploads/example.jpg',
        'mimeType' => 'image/jpeg',
    ]);
    $media->save();
    

Implementation Patterns

Core Workflows

  1. File Uploads

    • Use MediaManager to handle uploads:
      $media = $mediaManager->createFromRequest($request, 'file_field');
      $media->save();
      
    • Validate file types/sizes via donjohn_media.file_allowed_mimes and donjohn_media.file_max_size in config.
  2. Image Processing

    • Generate thumbnails/resized images via LiipImagine:
      $media->getPath('thumbnail'); // Returns processed path
      
    • Define custom filter sets in config/imagine.php for reuse.
  3. Entity Relationships

    • Attach media to Eloquent models via polymorphic relations:
      class Post extends Model
      {
          public function media()
          {
              return $this->morphToMany(Media::class, 'model');
          }
      }
      
    • Use media() helper to attach:
      $post->media()->attach($media->id);
      
  4. Form Integration

    • Use Symfony’s FileType (or Laravel’s File request handling) with custom validation:
      $request->validate([
          'file' => 'required|file|mimes:jpg,png|max:2048',
      ]);
      

Advanced Patterns

  • Custom Storage Override Donjohn\MediaBundle\Storage\FilesystemStorage to use S3/Flysystem:

    class CustomStorage extends FilesystemStorage
    {
        public function getAdapter()
        {
            return new \League\Flysystem\Adapter\S3(...);
        }
    }
    

    Bind it in config/donjohn_media.php:

    'storage' => App\Services\CustomStorage::class,
    
  • Events Listen for media.created/media.deleted to trigger actions:

    Media::created(function ($media) {
        // Send notification, log, etc.
    });
    
  • API Responses Serialize media with URLs:

    return response()->json([
        'url' => $media->getUrl(),
        'thumbnail' => $media->getUrl('thumbnail'),
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. LiipImagine Dependency

    • Issue: Missing liip/imagine-bundle (Symfony) or intervention/image (Laravel) causes image processing failures.
    • Fix: Install the required package and configure filter sets.
  2. File Paths in Laravel

    • Issue: Symfony’s public/ path differs from Laravel’s storage/app/public.
    • Fix: Update donjohn_media.upload_folder to storage/app/public/uploads and symlink:
      php artisan storage:link
      
  3. Polymorphic Relations

    • Issue: Forgetting to set morphClass in the relation can cause errors.
    • Fix: Explicitly define:
      $this->morphToMany(Media::class, 'model')->withPivot('created_at');
      
  4. Memory Limits

    • Issue: Large image processing may hit PHP’s memory_limit.
    • Fix: Increase in php.ini or use imagine’s cache option to avoid reprocessing.
  5. Deleted Files

    • Issue: Media records remain after file deletion.
    • Fix: Implement a media.deleted listener to clean up files:
      Media::deleted(function ($media) {
          if (file_exists($media->path)) {
              unlink($media->path);
          }
      });
      

Debugging Tips

  • Check Upload Paths Log config('donjohn_media.upload_folder') to verify file storage location.

  • Validate Filter Sets Ensure liip_imagine.filter_sets includes all used filters (e.g., thumbnail).

  • Symfony vs. Laravel Quirks

    • Use app_path() instead of __DIR__ for Laravel paths.
    • Replace container()->get() with Laravel’s app() or resolve().

Extension Points

  1. Custom Validators Extend Donjohn\MediaBundle\Validator\Constraints\File to add rules:

    class CustomFileValidator extends FileValidator
    {
        protected function validateSize($value)
        {
            if ($value > config('donjohn_media.file_max_size')) {
                $this->context->addViolation('File too large.');
            }
        }
    }
    
  2. Dynamic Filter Sets Generate filter sets at runtime:

    $media->addFilterSet('custom', [
        'filters' => ['thumbnail' => ['size' => [$width, $height]]],
    ]);
    
  3. Batch Processing Use queues for heavy image processing:

    dispatch(new ProcessMedia($media))->onQueue('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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity