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

Easy Admin File Upload Field Laravel Package

bytescommerce/easy-admin-file-upload-field

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bytescommerce/easy-admin-file-upload-field
    

    Publish the package's assets (if needed):

    php artisan vendor:publish --provider="BytesCommerce\FileUploadField\FileUploadFieldServiceProvider"
    
  2. First Use Case: Add a file upload field to an existing EasyAdmin CRUD controller (e.g., PostCrudController):

    use BytesCommerce\FileUploadField\Field\FileField;
    
    yield FileField::new('file', 'Document')
        ->setBasePath('uploads/documents')
        ->setUploadDir('public/uploads/documents');
    
    • Key Parameters:
      • new('field_name', 'label'): Maps to your model's attribute.
      • setBasePath(): Relative path for storage (e.g., storage/app/uploads).
      • setUploadDir(): Publicly accessible path (e.g., public/uploads).
  3. Verify:

    • Check config/easy-admin-file-upload-field.php for default settings.
    • Ensure File::BASE_FILE_PATH (or your custom path) exists in storage/app and public.

Implementation Patterns

Workflows

  1. Basic Upload:

    yield FileField::new('avatar', 'Profile Image')
        ->setBasePath('avatars')
        ->setUploadDir('public/avatars')
        ->setAllowedExtensions(['jpg', 'png', 'gif']);
    
    • Validation: Automatically validates file types/sizes (configurable in config/easy-admin-file-upload-field.php).
  2. Dynamic Paths: Use closures for dynamic paths (e.g., per-record uploads):

    yield FileField::new('attachment', 'Attachment')
        ->setBasePath(fn($entity) => "uploads/{$entity->id}")
        ->setUploadDir(fn($entity) => "public/uploads/{$entity->id}");
    
  3. Integration with Model Events: Hook into creating/updating to process files:

    public function createEntity(EntityManager $entityManager, $entityInstance): void
    {
        $entityInstance->processUploadedFile(); // Custom logic
        parent::createEntity($entityManager, $entityInstance);
    }
    
  4. Batch Processing: For bulk uploads (e.g., CSV imports), use the FileField in a custom form:

    yield FileField::new('import_file', 'CSV File')
        ->setBasePath('imports')
        ->setUploadDir('public/imports')
        ->setMaxFileSize(5); // 5MB
    

Advanced Patterns

  • Custom Storage: Override storage logic by extending FileField:

    use BytesCommerce\FileUploadField\Field\FileField as BaseFileField;
    
    class S3FileField extends BaseFileField {
        public function getStoragePath(): string {
            return Storage::disk('s3')->path($this->getBasePath());
        }
    }
    
  • Preview Thumbnails: Use setImageField() to display thumbnails for images:

    yield FileField::new('thumbnail', 'Thumbnail')
        ->setBasePath('thumbnails')
        ->setImageField('preview'); // Uses 'preview' attribute for thumbnail URL
    
  • Delete Handling: Implement deleteEntity() to clean up files:

    public function deleteEntity(EntityManager $entityManager, $entityInstance): void
    {
        if ($entityInstance->file) {
            Storage::delete($entityInstance->file);
        }
        parent::deleteEntity($entityManager, $entityInstance);
    }
    

Gotchas and Tips

Pitfalls

  1. Path Mismatches:

    • Issue: Files upload to storage/app but aren’t accessible via public.
    • Fix: Ensure setUploadDir() matches the symlinked path (e.g., public/uploads → symlink storage/app/uploads to public/uploads).
    • Debug: Run php artisan storage:link and verify paths.
  2. Permission Errors:

    • Issue: 500 Internal Server Error on upload.
    • Fix: Set correct permissions:
      chmod -R 775 storage/app/uploads
      chmod -R 775 public/uploads
      
  3. File Overwrites:

    • Issue: Uploads overwrite existing files with the same name.
    • Fix: Use setUploadedFileNamePattern() with [uuid].[extension]:
      ->setUploadedFileNamePattern('[uuid].[extension]')
      
  4. EasyAdmin Cache:

    • Issue: Changes to FileField aren’t reflected.
    • Fix: Clear EasyAdmin cache:
      php artisan easy-admin:clear-cache
      

Debugging Tips

  • Log Uploads: Enable debug mode in config/easy-admin-file-upload-field.php:
    'debug' => env('APP_DEBUG', false),
    
  • Check Events: Use dd() in createEntity()/updateEntity() to inspect $entityInstance for file attributes.
  • Storage Disk: Verify the correct disk is used (default: local). Override in config/filesystems.php:
    'disks' => [
        'local' => [
            'driver' => 'local',
            'root' => storage_path('app/uploads'),
        ],
    ],
    

Extension Points

  1. Custom Validation: Extend FileField to add rules:

    use BytesCommerce\FileUploadField\Field\FileField;
    
    class CustomFileField extends FileField {
        public function configure(): void {
            $this->setValidationRules([
                'file' => 'required|file|mimes:pdf,docx|max:10240', // 10MB
            ]);
        }
    }
    
  2. Post-Upload Processing: Use setAfterUploadCallback():

    yield FileField::new('document', 'Document')
        ->setAfterUploadCallback(function ($entity, $filePath) {
            // Convert PDF to text, etc.
        });
    
  3. Frontend Customization: Override the default Twig template by publishing assets:

    php artisan vendor:publish --tag=easy-admin-file-upload-field-views
    

    Then modify resources/views/vendor/easy-admin-file-upload-field/field.html.twig.

  4. Localization: Translate labels dynamically:

    yield FileField::new('file', trans('admin.file_upload.label'))
        ->setBasePath(trans('admin.file_upload.path'));
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui