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

Filament Media Manager Laravel Package

tomatophp/filament-media-manager

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tomatophp/filament-media-manager
    php artisan vendor:publish --provider="TomatoPHP\FilamentMediaManager\FilamentMediaManagerServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. Register the Panel: Add to app/Providers/Filament/AdminPanelProvider.php:

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->id('admin')
            ->path('admin')
            ->middleware([
                // ...
            ])
            ->registration()
            ->discoverResources(in: app_path('Filament/Resources'), for: 'TomatoPHP\FilamentMediaManager')
            ->discoverPages(in: app_path('Filament/Pages'), for: 'TomatoPHP\FilamentMediaManager')
            ->resources([
                \TomatoPHP\FilamentMediaManager\Resources\MediaResource::class,
            ]);
    }
    
  3. First Use Case: Access /admin/media to upload files via the GUI. Use the Media model (TomatoPHP\FilamentMediaManager\Models\Media) to attach files to Eloquent models.


Implementation Patterns

Core Workflows

  1. Media Uploads:

    • Use the built-in MediaResource for CRUD operations.
    • Customize upload rules via config/filament-media-manager.php:
      'allowed_file_types' => ['jpg', 'png', 'pdf'],
      'max_file_size' => '10MB',
      
  2. Model Integration:

    • Attach media to models using Spatie’s HasMedia trait:
      use Spatie\MediaLibrary\HasMedia;
      use TomatoPHP\FilamentMediaManager\Models\Media;
      
      class Post extends Model implements HasMedia
      {
          public function registerMediaConversions(Media $media = null): void
          {
              $this->addMediaConversion('thumb')
                   ->width(200)
                   ->height(200);
          }
      }
      
    • Use attachMedia() in Filament forms:
      use TomatoPHP\FilamentMediaManager\Forms\Components\MediaUpload;
      
      MediaUpload::make('image')
          ->collection('images')
          ->required()
      
  3. Collections:

    • Define collections in config/filament-media-manager.php:
      'collections' => [
          'posts' => [
              'model' => \App\Models\Post::class,
              'foreign_key' => 'id',
          ],
      ],
      
    • Access collections via Media::where('collection_name', 'posts')->get().
  4. Conversions:

    • Generate thumbnails or resized images on upload:
      $media = $post->addMediaFromRequest('image')->toMediaCollection('images');
      $media->registerMediaConversions();
      $media->convertImage();
      

Advanced Patterns

  • Custom Fields: Extend the MediaResource to add custom columns:

    public static function table(Table $table): Table
    {
        $table->columns([
            // Default columns...
            TextColumn::make('custom_field')
                ->getStateUsing(fn (Media $record) => $record->custom_field),
        ]);
    }
    
  • Policy Integration: Use Filament’s policies to restrict access:

    public static function canAccess(): bool
    {
        return auth()->user()->can('manage-media');
    }
    
  • Events: Listen to media events (e.g., MediaCreated):

    \TomatoPHP\FilamentMediaManager\Events\MediaCreated::dispatch($media);
    

Gotchas and Tips

Common Pitfalls

  1. Migration Conflicts:

    • If spatie/laravel-medialibrary is already installed, ensure the media table schema matches. Run:
      php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"
      
    • Resolve conflicts by comparing database/migrations/ files.
  2. Collection Foreign Keys:

    • Forgetting to define foreign_key in collections config will break attachments. Use:
      'collections' => [
          'posts' => [
              'model' => \App\Models\Post::class,
              'foreign_key' => 'post_id', // Must match your model's key
          ],
      ],
      
  3. File Size Limits:

    • PHP’s upload_max_filesize and post_max_size must exceed max_file_size in config. Adjust in php.ini if needed.
  4. Caching Issues:

    • Clear Filament cache after config changes:
      php artisan filament:cache:clear
      

Debugging Tips

  • Log Media Events: Add a listener to debug media operations:

    \TomatoPHP\FilamentMediaManager\Events\MediaCreated::class => [
        \App\Listeners\LogMediaCreation::class,
    ],
    
  • Check Disk Configuration: Verify config/filesystems.php points to the correct disk (e.g., public or s3):

    'default' => env('FILESYSTEM_DISK', 'public'),
    
  • Validate Media Conversions: Ensure imagick or gd is installed for image conversions:

    sudo apt-get install imagemagick  # Linux
    brew install imagemagick         # macOS
    

Extension Points

  1. Custom Media Models: Extend TomatoPHP\FilamentMediaManager\Models\Media to add fields:

    class CustomMedia extends Media
    {
        protected $casts = [
            'custom_field' => 'string',
        ];
    }
    

    Update the config to use your model:

    'model' => \App\Models\CustomMedia::class,
    
  2. Override Resource Classes: Publish and modify the resource:

    php artisan vendor:publish --provider="TomatoPHP\FilamentMediaManager\FilamentMediaManagerServiceProvider" --tag="resources"
    
  3. Add Custom Actions: Extend the MediaResource to include actions:

    public static function getActions(): array
    {
        return [
            DeleteAction::make(),
            Action::make('customAction')
                ->action(fn (Media $record) => $record->customAction())
                ->icon('heroicon-o-pencil'),
        ];
    }
    
  4. Bulk Operations: Use Filament’s bulk actions for batch processing:

    public static function table(Table $table): Table
    {
        $table->actions([
            Tables\Actions\BulkActionGroup::make([
                Tables\Actions\DeleteBulkAction::make(),
                Tables\Actions\Action::make('export')
                    ->action(fn (Collection $records) => $records->export()),
            ]),
        ]);
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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