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

Pando File Bundle Laravel Package

blackboxcode/pando-file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require blackboxcode/pando-file-bundle
    

    Register the bundle in config/app.php under providers:

    BlackBoxCode\PandoFileBundle\PandoFileBundle::class,
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="BlackBoxCode\PandoFileBundle\PandoFileBundle" --tag="config"
    

    Update config/pando-file.php with your storage paths, allowed MIME types, and file size limits.

  3. First Use Case: File Upload Inject the PandoFileManager service into a controller:

    use BlackBoxCode\PandoFileBundle\Services\PandoFileManager;
    
    public function upload(Request $request, PandoFileManager $fileManager)
    {
        $file = $request->file('file');
        $path = $fileManager->store($file, 'uploads');
        return response()->json(['path' => $path]);
    }
    

Implementation Patterns

Core Workflows

  1. File Storage

    • Single File Upload:
      $path = $fileManager->store($file, 'custom/directory');
      
    • Multiple Files:
      $paths = $fileManager->storeMultiple($request->file('files'), 'uploads');
      
    • Custom Disk Usage: Configure disks in config/pando-file.php to use S3, FTP, or local storage:
      'disks' => [
          's3' => [
              'driver' => 's3',
              'key' => env('AWS_ACCESS_KEY_ID'),
              'secret' => env('AWS_SECRET_ACCESS_KEY'),
              'bucket' => env('AWS_BUCKET'),
          ],
      ],
      
      Then pass the disk name:
      $path = $fileManager->store($file, 'uploads', 's3');
      
  2. File Retrieval

    • Generate URLs:
      $url = $fileManager->url($path);
      $temporaryUrl = $fileManager->temporaryUrl($path, now()->addMinutes(10));
      
    • Stream Files:
      return $fileManager->stream($path, 'myfile.pdf');
      
  3. File Management

    • Delete Files:
      $fileManager->delete($path);
      $fileManager->deleteMultiple(['path1', 'path2']);
      
    • Check Existence:
      if ($fileManager->exists($path)) { ... }
      
  4. Validation Integration Use the PandoFileValidator to enforce rules:

    use BlackBoxCode\PandoFileBundle\Validators\PandoFileValidator;
    
    $validator = new PandoFileValidator();
    $validator->validate($file, [
        'mimes' => ['jpg', 'png'],
        'max_size' => '2048', // KB
    ]);
    

Integration Tips

  1. Laravel Events Bind to file upload events in EventServiceProvider:

    protected $listen = [
        'BlackBoxCode\PandoFileBundle\Events\FileUploaded' => [
            'App\Listeners\LogUploadedFile',
        ],
    ];
    
  2. Form Requests Extend FormRequest to validate files:

    public function rules()
    {
        return [
            'file' => [
                'required',
                function ($attribute, $value, $fail) {
                    $validator = new PandoFileValidator();
                    if (!$validator->validate($value, [
                        'mimes' => ['pdf', 'docx'],
                        'max_size' => '5120',
                    ])) {
                        $fail('Invalid file type or size.');
                    }
                },
            ],
        ];
    }
    
  3. API Resources Transform file paths in API responses:

    public function toArray($request)
    {
        return [
            'path' => $this->fileManager->url($this->path),
            'size' => $this->size,
            'mime' => $this->mime,
        ];
    }
    
  4. Middleware Restrict file access by role:

    public function handle($request, Closure $next)
    {
        if ($request->is('files/*') && !$request->user()->can('access-files')) {
            abort(403);
        }
        return $next($request);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Configuration Overrides

    • Ensure config/pando-file.php is published and updated. Default values may not match your needs.
    • Fix: Always check the config after publishing:
      php artisan config:clear
      
  2. Disk Misconfiguration

    • If using custom disks (e.g., S3), verify credentials and permissions. Silent failures can occur if the disk is misconfigured.
    • Fix: Test disk connections manually:
      use Illuminate\Support\Facades\Storage;
      Storage::disk('s3')->put('test', 'test');
      
  3. File Path Collisions

    • The bundle uses Laravel’s default storage paths. Overlapping paths (e.g., public and uploads) can cause issues.
    • Fix: Use unique directories or custom disks:
      $path = $fileManager->store($file, 'app/uploads');
      
  4. Validation Bypass

    • Skipping validation (e.g., store($file, 'uploads', false)) can lead to security risks like directory traversal.
    • Fix: Always validate files unless explicitly required otherwise.
  5. Event Listener Conflicts

    • If multiple bundles emit FileUploaded events, listeners may fire unexpectedly.
    • Fix: Use priority in listeners or namespace events:
      event(new \BlackBoxCode\PandoFileBundle\Events\FileUploaded($path));
      

Debugging Tips

  1. Log File Operations Enable debug mode in config/pando-file.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  2. Check Storage Permissions Ensure the storage directory has write permissions:

    chmod -R 775 storage/app/public
    
  3. Validate File Paths Use dd() to inspect paths before operations:

    $path = $fileManager->getPath($file);
    dd($path); // Verify the path is correct
    
  4. Test with Small Files First Start with small files (e.g., 1KB) to rule out size-related issues before testing large uploads.


Extension Points

  1. Custom Validators Extend PandoFileValidator to add rules:

    namespace App\Validators;
    
    use BlackBoxCode\PandoFileBundle\Validators\PandoFileValidator;
    
    class CustomFileValidator extends PandoFileValidator
    {
        public function validateExtension($extension)
        {
            return in_array($extension, ['jpg', 'jpeg', 'png']);
        }
    }
    

    Use it in your code:

    $validator = new CustomFileValidator();
    
  2. File Processing Hooks Override the PandoFileManager to add preprocessing:

    namespace App\Services;
    
    use BlackBoxCode\PandoFileBundle\Services\PandoFileManager;
    
    class CustomFileManager extends PandoFileManager
    {
        public function store($file, $directory = 'uploads', $validate = true)
        {
            // Preprocess file (e.g., resize images)
            if ($file->isValid() && $file->getClientOriginalExtension() === 'jpg') {
                $file = $this->resizeImage($file);
            }
            return parent::store($file, $directory, $validate);
        }
    
        protected function resizeImage($file)
        {
            // Implement resize logic
        }
    }
    

    Bind it in AppServiceProvider:

    $this->app->bind(PandoFileManager::class, function ($app) {
        return new CustomFileManager(
            $app->make('storage'),
            $app->make('validator')
        );
    });
    
  3. Custom Storage Drivers Implement BlackBoxCode\PandoFileBundle\Contracts\FileStorage to add support for new storage backends (e.g., Dropbox, Backblaze).

  4. Event Customization Extend the FileUploaded event to include additional data:

    namespace App\Events;
    
    use BlackBoxCode\PandoFileBundle\Events\FileUploaded as BaseFileUploaded;
    
    class FileUploaded extends BaseFileUploaded
    {
        public $userId;
    
        public function __construct($path, $userId)
        {
            parent::__construct($
    
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.
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle