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

Moonshine Spatie Medialibrary Laravel Package

visual-ideas/moonshine-spatie-medialibrary

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require visual-ideas/moonshine-spatie-medialibrary
    

    Ensure spatie/laravel-medialibrary is also installed and configured in your Laravel app.

  2. Publish Config (if needed):

    php artisan vendor:publish --provider="MoonShine\Providers\MoonShineServiceProvider" --tag="moonshine-config"
    

    Update moonshine.php to include the new field in your fields configuration.

  3. First Use Case: Register the field in a MoonShine resource:

    use VisualIdeas\MoonShineSpatieMediaLibrary\Fields\MediaLibrary;
    
    public function fields(): array
    {
        return [
            MediaLibrary::make('Gallery')
                ->collection('gallery') // Spatie collection name
                ->disk('public')        // Disk where files are stored
                ->maxFiles(5),          // Optional: Limit uploads
        ];
    }
    

Implementation Patterns

Core Workflows

  1. Basic Media Upload:

    • Use MediaLibrary::make('Field Name') to create a field tied to a Spatie collection.
    • Configure disk, collection, and validation (e.g., ->maxFiles(3)).
  2. Dynamic Collections:

    • Bind collections dynamically via closures:
      MediaLibrary::make('Avatar')
          ->collection(fn (Model $model) => $model->avatar_collection)
      
  3. Nested Media Handling:

    • For nested models, pass the parent model context:
      MediaLibrary::make('Cover')
          ->collection('covers')
          ->model($parentModel) // Explicitly set parent model
      
  4. Integration with Spatie Events:

    • Listen to Spatie’s MediaStoringEvent or MediaDeletingEvent to trigger custom logic:
      use Spatie\MediaLibrary\Events\MediaStoringEvent;
      
      event(new MediaStoringEvent($model, $collection, $path));
      

Advanced Patterns

  1. Custom Thumbnails:

    • Override default thumbnails by extending the field:
      class CustomMediaLibrary extends MediaLibrary
      {
          public function thumbnailUrl(): string
          {
              return $this->model->getFirstMediaUrl('custom_thumbnail');
          }
      }
      
  2. Conditional Fields:

    • Show/hide based on model state:
      MediaLibrary::make('Hero Image')
          ->visible(fn (Model $model) => $model->is_published)
      
  3. Bulk Operations:

    • Use ->multiple() for multi-select uploads (requires Spatie v3+):
      MediaLibrary::make('Documents')
          ->collection('documents')
          ->multiple()
      
  4. API-Driven Uploads:

    • For SPAs, expose the field via MoonShine’s API and handle uploads client-side with Axios:
      axios.post('/moonshine/api/upload', { file, collection: 'gallery' });
      

Gotchas and Tips

Common Pitfalls

  1. Disk Mismatch:

    • Ensure the disk in the field matches the Spatie MediaLibrary config. Defaults to public; verify in config/filesystems.php.
  2. Collection Not Found:

    • If the collection isn’t registered in your model’s $mediaable trait, the field will fail silently. Add:
      use Spatie\MediaLibrary\HasMedia;
      use Spatie\MediaLibrary\InteractsWithMedia;
      
      class Post extends Model implements HasMedia
      {
          use InteractsWithMedia;
          protected $mediaableType = 'posts';
      }
      
  3. Permission Issues:

    • Spatie’s Media model requires proper storage permissions. Run:
      chmod -R 775 storage/app/public
      
  4. MoonShine Version Lock:

    • The package enforces strict version compatibility. Upgrading MoonShine may break the field until you update the package (e.g., >= v3.0.0 for MoonShine v3).

Debugging Tips

  1. Log Media Events: Add a listener to debug uploads/deletions:

    Spatie\MediaLibrary\Events\MediaStoringEvent::class => [
        \App\Listeners\LogMediaUpload::class,
    ],
    
  2. Check Network Requests:

    • Use browser dev tools to verify upload endpoints (e.g., /moonshine/api/upload-media). Ensure CORS is configured if using a SPA.
  3. Validate Collections:

    • Run php artisan vendor:publish --tag="spatie-media-library-config" to inspect config/media-library.php for collection names.

Extension Points

  1. Custom Validation:

    • Override resolveRules() in a custom field class to add rules:
      public function resolveRules(): array
      {
          return [
              'required_if:is_featured,true',
          ];
      }
      
  2. Presets for Thumbnails:

    • Use Spatie’s registerMediaConversions to define presets, then reference them in the field:
      MediaLibrary::make('Profile Pic')
          ->preset('avatar') // Uses a registered conversion
      
  3. Localization:

    • Override labels/placeholders via MoonShine’s localization system:
      'moonshine' => [
          'fields' => [
              'media_library' => [
                  'labels' => [
                      'en' => 'Media Library',
                      'ru' => 'Медиабиблиотека',
                  ],
              ],
          ],
      ],
      
  4. Custom UI Components:

    • Replace the default Dropzone.js by extending the field’s view method:
      public function view(): string
      {
          return 'moonshine-spatie-medialibrary::custom-upload';
      }
      
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