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

File Upload Bundle Laravel Package

connectholland/file-upload-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require connectholland/file-upload-bundle
    

    Enable in AppKernel.php:

    new ConnectHolland\FileUploadBundle(),
    
  2. Configure Storage Path Add to config.yml:

    file_upload:
        path: "%kernel.root_dir%/../../uploads/%kernel.environment%"
    

    Ensure the directory exists and is writable.

  3. First Use Case: Basic File Upload

    • Create an entity implementing UploadObjectInterface (or use UploadTrait):
      use ConnectHolland\FileUploadBundle\Model\UploadTrait;
      
      class Product
      {
          use UploadTrait;
      }
      
    • Add a file field to your form type:
      $builder->add('fileUpload', FileUploadType::class);
      
    • Submit the form, and the file will be saved to the configured path.

Implementation Patterns

Workflows

  1. Entity Integration

    • Use UploadTrait for boilerplate methods (getFileUpload, setFileUpload, getFilePath, etc.).
    • Customize trait methods if needed (e.g., rename getFileUpload to getImageUpload via trait aliasing).
  2. Form Handling

    • Use FileUploadType for file fields in forms:
      $builder->add('document', FileUploadType::class, [
          'label' => 'Upload Document',
          'required' => false,
          'allowed_mime_types' => ['application/pdf'],
          'max_size' => '10M',
      ]);
      
    • Validate uploads via Symfony’s built-in validators (e.g., File constraint).
  3. File Management

    • Upload: Handled automatically when the form is submitted.
    • Delete: Implement prePersist/preUpdate in your entity to delete old files:
      public function preUpdate()
      {
          if ($this->fileUpload && $this->fileUpload->getFilePath()) {
              $this->fileUpload->deleteFile();
          }
      }
      
    • Access Files: Use $entity->getFilePath() to retrieve the stored file path.
  4. Batch Processing

    • Loop through entities to upload/delete files in bulk:
      foreach ($products as $product) {
          $form->submit($product);
          if ($form->isValid()) {
              $product->getFileUpload()->upload();
          }
      }
      
  5. Custom Storage

    • Override the default storage by extending the FileUpload class or using a custom service.

Gotchas and Tips

Pitfalls

  1. Directory Permissions

    • Ensure the configured file_upload.path directory is writable by the web server user.
    • Debug: Check Symfony’s logs for Permission denied errors.
  2. File Overwriting

    • The bundle does not handle filename collisions by default. Use a custom FileUpload class to append hashes or timestamps:
      $this->fileUpload->setFileName(uniqid().'_'.$this->fileUpload->getFileName());
      
  3. Entity Lifecycle Hooks

    • Forgetting to call deleteFile() in preUpdate/preRemove can leave orphaned files.
    • Test file deletion manually:
      $entity->getFileUpload()->deleteFile(); // Force delete for testing.
      
  4. Symfony 3+ Compatibility

    • The bundle is archived and may lack support for newer Symfony versions (e.g., Flex, PHP 8.x).
    • Test thoroughly if using Symfony 4/5.
  5. Form Validation

    • Always validate file types/sizes in the form type, not just the entity:
      $builder->add('fileUpload', FileUploadType::class, [
          'constraints' => [
              new File(['maxSize' => '1024k']),
              new File(['mimeTypes' => ['image/jpeg']]),
          ],
      ]);
      

Tips

  1. Configuration Flexibility

    • Use environment-specific paths (e.g., %kernel.environment% in config.yml) to separate dev/staging/prod uploads.
  2. Custom File Upload Class

    • Extend ConnectHolland\FileUploadBundle\Model\FileUpload to add logic (e.g., auto-resize images):
      class CustomFileUpload extends FileUpload
      {
          public function upload()
          {
              $this->resizeImage(); // Custom logic
              parent::upload();
          }
      }
      
    • Update the entity to use your class:
      use AppBundle\Model\CustomFileUpload;
      
      class Product
      {
          private $fileUpload;
      
          public function getFileUpload()
          {
              return $this->fileUpload;
          }
      
          public function setFileUpload(CustomFileUpload $fileUpload)
          {
              $this->fileUpload = $fileUpload;
          }
      }
      
  3. Debugging

    • Enable debug mode to see file upload paths in Symfony’s profiler.
    • Log upload paths for verification:
      $logger->info('File uploaded to: '.$entity->getFilePath());
      
  4. Security

    • Restrict upload directories to prevent directory traversal:
      file_upload:
          path: "%kernel.root_dir%/../../uploads/%kernel.environment%"
          allowed_extensions: [jpg, png, pdf] # Optional: Filter extensions.
      
    • Use Symfony’s File validator to enforce security constraints.
  5. Testing

    • Mock file uploads in PHPUnit:
      $file = new UploadedFile(__DIR__.'/fixtures/test.jpg', 'test.jpg');
      $form->submit(['fileUpload' => $file]);
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky