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

201created/media-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require 201created/media-bundle
    

    Publish the configuration:

    php artisan vendor:publish --provider="201Created\MediaBundle\MediaBundleServiceProvider" --tag="config"
    

    Run migrations (if using database storage):

    php artisan migrate
    
  2. Basic Setup Register the bundle in config/app.php under providers:

    201Created\MediaBundle\MediaBundleServiceProvider::class,
    
  3. First Use Case: File Upload Inject the MediaService into a controller or service:

    use 201Created\MediaBundle\Services\MediaService;
    
    public function uploadFile(Request $request, MediaService $mediaService)
    {
        $file = $request->file('file');
        $media = $mediaService->upload($file, [
            'disk' => 'public',
            'path' => 'uploads',
        ]);
        return response()->json($media);
    }
    

Implementation Patterns

Core Workflows

  1. File Upload & Storage Use MediaService for handling uploads with configurable disks (S3, local, etc.):

    $media = $mediaService->upload($file, [
        'disk' => 's3',
        'path' => 'user_uploads/{user_id}',
        'visibility' => 'public', // For S3
    ]);
    
  2. Media Metadata & Thumbnails Automatically extract metadata (e.g., EXIF for images) and generate thumbnails:

    $media = $mediaService->upload($file, [
        'generate_thumbnails' => true,
        'thumbnail_sizes' => ['small', 'medium', 'large'],
    ]);
    
  3. Validation & Policies Validate file types/sizes via MediaValidator:

    $validator = new MediaValidator();
    $validator->allowedTypes(['image/jpeg', 'image/png']);
    $validator->maxSize(5 * 1024 * 1024); // 5MB
    $validator->validate($file);
    
  4. Database Integration Attach media to Eloquent models via HasMedia trait:

    use 201Created\MediaBundle\Traits\HasMedia;
    
    class Post extends Model
    {
        use HasMedia;
    }
    

    Then upload and associate:

    $post = new Post();
    $post->addMedia($file)->toMediaCollection('images');
    
  5. Batch Processing Process multiple files in bulk:

    $files = $request->file('files');
    $media = $mediaService->uploadMultiple($files, [
        'disk' => 'public',
        'path' => 'batch_uploads',
    ]);
    

Integration Tips

  • Custom Disks: Extend MediaService to support custom storage backends (e.g., FTP, Google Drive).
  • Events: Listen to MediaUploaded, MediaDeleted, etc., for post-processing:
    event(new MediaUploaded($media));
    
  • API Responses: Serialize media objects to JSON:
    return response()->json($media->toArray());
    
  • Testing: Use MediaService mocks in PHPUnit:
    $mockMedia = Mockery::mock(Media::class);
    $mediaService->shouldReceive('upload')->andReturn($mockMedia);
    

Gotchas and Tips

Pitfalls

  1. Disk Configuration

    • Ensure config/filesystems.php is properly set up for the target disk (e.g., S3 credentials, local paths).
    • Default disk must be defined in config/media.php:
      'default_disk' => 'public',
      
  2. Thumbnail Generation

    • Requires intervention/image or spatie/image. Install via:
      composer require intervention/image
      
    • Thumbnail paths are auto-generated but can be customized in config/media.php:
      'thumbnail_path' => 'thumbnails/{filename}',
      
  3. File Permissions

    • For local storage, ensure the storage/app/public directory is writable:
      chmod -R 775 storage/app/public
      
  4. Memory Limits

    • Large file uploads may hit PHP’s memory_limit. Increase if needed:
      ini_set('memory_limit', '512M');
      
  5. Database Locking

    • Concurrent uploads to the same path may cause race conditions. Use unique paths or transactions:
      DB::transaction(function () use ($mediaService, $file) {
          $mediaService->upload($file, ['path' => uniqid()]);
      });
      

Debugging Tips

  • Log Uploads: Enable logging in config/media.php:
    'log_uploads' => true,
    
  • Check Events: Use Laravel’s event listener debugging:
    php artisan event:listen MediaUploaded
    
  • Validate Config: Run:
    php artisan config:clear
    
    if changes to config/media.php aren’t reflected.

Extension Points

  1. Custom Storage Adapters Implement 201Created\MediaBundle\Contracts\StorageAdapter for new backends.

  2. Media Model Extensions Extend the Media model to add custom fields:

    class CustomMedia extends Media
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    
  3. Middleware for Uploads Restrict uploads by role/user:

    public function handle($request, Closure $next)
    {
        if (!$request->user()->can('upload_files')) {
            abort(403);
        }
        return $next($request);
    }
    
  4. Queue Uploads Offload processing to queues for large files:

    $mediaService->upload($file)->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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware