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

zeeshantariq/filament-attachmate

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Publish Migrations & Config Run the publisher command to set up the attachments table and default configuration:

    php artisan vendor:publish --provider="Zeeshantariq\FilamentAttachmate\FilamentAttachmateServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="Zeeshantariq\FilamentAttachmate\FilamentAttachmateServiceProvider" --tag="config"
    

    Then migrate:

    php artisan migrate
    
  2. Define a Polymorphic Attachment Model Extend the Attachment model (auto-generated by the migration) in your App\Models:

    use Zeeshantariq\FilamentAttachmate\Models\Attachment;
    
    class AppAttachment extends Attachment {}
    
  3. First Use Case: Attach Files to a Model Add the HasAttachments trait to your Filament resource model:

    use Zeeshantariq\FilamentAttachmate\Traits\HasAttachments;
    
    class Post extends Model
    {
        use HasAttachments;
    }
    

    Then register the attachment panel in your Filament resource:

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                // ... other fields
                Attachmate::make('attachments')
                    ->label('Attachments')
                    ->maxAttachments(10),
            ]);
    }
    

Implementation Patterns

Core Workflows

  1. Polymorphic Attachment Management

    • Use Attachmate::make() in Filament forms/tables to render attachment panels.
    • Supports drag-and-drop uploads, bulk actions (delete, download), and thumbnails:
      Attachmate::make('attachments')
          ->label('Media')
          ->accept(['image/*', 'application/pdf'])
          ->maxAttachments(5)
          ->thumbnailWidth(100)
      
  2. Integration with Filament Resources

    • Create/Edit Forms: Embed attachments directly in resource forms.
    • Table Columns: Display attachment counts or previews:
      use Zeeshantariq\FilamentAttachmate\Columns\AttachmentsCountColumn;
      
      Table::column(AttachmentsCountColumn::make())
      
  3. Custom Storage & Validation

    • Override storage logic via the Attachment model:
      protected static function boot()
      {
          parent::boot();
          static::creating(function ($attachment) {
              $attachment->disk = 's3';
          });
      }
      
    • Add custom validation rules in the Attachmate panel:
      Attachmate::make()
          ->rules(['attachments.*' => 'mimes:jpeg,png|max:2048'])
      
  4. Bulk Operations

    • Leverage the built-in attachments relationship in queries:
      $post = Post::with('attachments')->find(1);
      $post->attachments()->delete(); // Bulk delete
      
  5. API & External Access

    • Use the Attachment model directly in APIs or services:
      $attachments = Auth::user()->attachments()->latest()->get();
      

Advanced Patterns

  1. Dynamic Attachment Limits

    • Conditionally set maxAttachments based on user roles or model state:
      Attachmate::make()
          ->maxAttachments(fn ($record) => $record->isPremium() ? 20 : 5)
      
  2. Custom Attachment Models

    • Extend the Attachment model to add metadata:
      class CustomAttachment extends Attachment
      {
          protected $casts = [
              'alt_text' => 'string',
          ];
      }
      
    • Update the HasAttachments trait to use your model:
      use Zeeshantariq\FilamentAttachmate\Traits\HasAttachments as BaseHasAttachments;
      
      trait HasAttachments extends BaseHasAttachments
      {
          public function attachments()
          {
              return $this->morphMany(CustomAttachment::class, 'attachable');
          }
      }
      
  3. Event Listeners

    • Hook into attachment lifecycle events (e.g., AttachmentCreated):
      use Zeeshantariq\FilamentAttachmate\Events\AttachmentCreated;
      
      AttachmentCreated::listen(function ($attachment) {
          // Send notification, log, etc.
      });
      
  4. Filament Notifications

    • Show success/error messages after attachment actions:
      use Filament\Notifications\Notification;
      
      Attachmate::make()
          ->afterAttach(function ($record, $attachments) {
              Notification::make()
                  ->title('Attachments added')
                  ->success()
                  ->send();
          });
      

Gotchas and Tips

Common Pitfalls

  1. Migration Conflicts

    • If you manually modify the attachments table, reset it via:
      php artisan migrate:fresh --env=testing
      
    • Tip: Use --env=testing to avoid production data loss.
  2. Polymorphic Key Mismatches

    • Ensure your model’s getRouteKeyName() matches the polymorphic key used in queries:
      public function getRouteKeyName()
      {
          return 'slug'; // Must match the column used in `attachments` table
      }
      
  3. File Upload Limits

    • PHP’s upload_max_filesize and post_max_size may block large uploads. Adjust in php.ini or use chunked uploads:
      Attachmate::make()
          ->chunkUploads(true)
          ->chunkSize(5) // MB
      
  4. Caching Issues

    • Clear Filament’s view cache after updating attachment panels:
      php artisan filament:cache:clear
      
  5. Permission Denied Errors

    • Ensure the attachments table’s attachable_id/attachable_type columns are indexed:
      Schema::table('attachments', function (Blueprint $table) {
          $table->index(['attachable_id', 'attachable_type']);
      });
      

Debugging Tips

  1. Log Upload Paths

    • Temporarily log the storage path in the Attachment model:
      protected static function boot()
      {
          static::created(function ($attachment) {
              \Log::debug('Attachment stored at:', [$attachment->path]);
          });
      }
      
  2. Validate Disk Configuration

    • Check config/filesystems.php for correct disk settings (e.g., local, s3):
      'disks' => [
          's3' => [
              'driver' => 's3',
              'key' => env('AWS_ACCESS_KEY_ID'),
              'secret' => env('AWS_SECRET_ACCESS_KEY'),
              // ...
          ],
      ],
      
  3. Test Polymorphic Relationships

    • Verify relationships work outside Filament:
      $post = Post::find(1);
      $post->attachments()->count(); // Should return > 0
      
  4. Check Filament Logs

    • Enable debug mode in config/filament.php:
      'debug' => env('FILAMENT_DEBUG', false),
      
    • Inspect logs at storage/logs/filament.log.

Extension Points

  1. Custom Storage Drivers

    • Override the default storage logic by extending the Attachment model:
      use Illuminate\Support\Facades\Storage;
      
      class CustomAttachment extends Attachment
      {
          public function getPathAttribute($value)
          {
            return 'custom/' . parent::getPathAttribute($value);
          }
      }
      
  2. Add Metadata Fields

    • Extend the attachments table and model:
      Schema::table('attachments', function (Blueprint $table) {
          $table->string('alt_text')->nullable();
          $table->unsignedTinyInteger('priority')->default(1);
      });
      
      Then update the Attachment model’s $fillable.
  3. Override UI Components

    • Replace the default attachment panel by publishing and modifying views:
      php artisan vendor:publish --tag="filament-attachmate-views"
      
    • Edit resources/views/vendor/filament-attachmate/....
  4. Add Custom Actions

    • Extend the attachment table with custom buttons:
      use Zeeshantariq\FilamentAttachmate\Actions\DownloadAttachment;
      
      Table::column(AttachmentsColumn::make())
          ->actions([
              DownloadAttachment::make(),
              Action::make('share')
                  ->url(fn ($record) => route('attachments.share', $record))
                  ->icon('heroicon-o-share'),
          ]);
      
  5. Integrate with Filament Spatie Media Library

    • Use both packages together by syncing attachments:
      $post->attachments()->each(fn ($
      
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge