Weave 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

Uploader Laravel Package

atom-php/uploader

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require atom-php/uploader
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Atom\Uploader\UploaderServiceProvider::class,
    ],
    
  2. Basic Configuration Publish the config file:

    php artisan vendor:publish --provider="Atom\Uploader\UploaderServiceProvider"
    

    Key config options in config/uploader.php:

    • default_disk: Set your default storage disk (e.g., public, s3).
    • allowed_mimes: Define allowed file types (e.g., ['image/jpeg', 'image/png']).
    • max_size: Set max file size in KB (e.g., 10240 for 10MB).
  3. First Use Case: Uploading a File

    use Atom\Uploader\Uploader;
    
    $uploader = app(Uploader::class);
    $result = $uploader->upload(
        file: $request->file('avatar'),
        options: [
            'disk' => 'public',
            'path' => 'avatars',
            'filename' => 'custom_name.jpg',
        ]
    );
    
    • Returns an array with path, url, and original_name.

Implementation Patterns

ORM Integration (Eloquent)

  1. Embeddable Uploads Create an Upload model with an Uploadable trait:

    use Atom\Uploader\Traits\Uploadable;
    
    class Profile extends Model
    {
        use Uploadable;
    
        protected $uploadable = [
            'avatar' => [
                'disk' => 'public',
                'path' => 'profile_avatars',
            ],
        ];
    }
    
    • Automatically handles file storage when saving:
      $profile = new Profile();
      $profile->avatar = $request->file('avatar');
      $profile->save(); // File is uploaded and path stored in DB.
      
  2. Dynamic Uploads Use the Uploader facade for ad-hoc uploads:

    use Atom\Uploader\Facades\Uploader;
    
    $path = Uploader::upload($file, [
        'disk' => 's3',
        'path' => 'dynamic_uploads',
    ]);
    
  3. Batch Processing Process multiple files in a loop:

    $files = $request->file('documents');
    $results = [];
    
    foreach ($files as $file) {
        $results[] = $uploader->upload($file, ['path' => 'documents']);
    }
    

Workflows

  1. Pre-Upload Validation Extend validation logic before upload:

    $validator = Validator::make($request->all(), [
        'file' => [
            'required',
            'file',
            'mimes:jpeg,png,pdf',
            function ($attribute, $value, $fail) {
                if ($value->getSize() > 5 * 1024 * 1024) {
                    $fail('File too large. Max 5MB.');
                }
            },
        ],
    ]);
    
  2. Post-Upload Actions Chain actions after upload (e.g., generate thumbnails):

    $result = $uploader->upload($file, ['path' => 'images']);
    $this->generateThumbnail($result['path']);
    
  3. Fallback Disks Define fallback disks in config:

    'fallbacks' => [
        'public' => 's3',
        's3' => 'local',
    ],
    
    • Automatically falls back if the primary disk fails.

Gotchas and Tips

Pitfalls

  1. Disk Misconfiguration

    • Ensure your filesystems.php is properly configured for the disks you reference in uploader.php.
    • Test disk connectivity with:
      php artisan storage:link
      
  2. Filename Collisions

    • If filename is not provided, the package uses a UUID. Override this in options:
      'filename' => 'user_' . auth()->id() . '.jpg'
      
    • Tip: Use Str::uuid() for unique filenames:
      'filename' => Str::uuid() . '.' . $file->extension()
      
  3. Large File Handling

    • For files >2MB, ensure post_max_size and upload_max_filesize in php.ini are adjusted.
    • Use chunked uploads for very large files (not natively supported; consider integrating with Laravel Filesystem Chunking).
  4. ORM Sync Issues

    • If using Uploadable trait, ensure your model’s fillable includes the upload field name (e.g., avatar).
    • Debugging: Check for MassAssignmentException if the field isn’t fillable.

Debugging

  1. Log Upload Events Enable logging in config/uploader.php:

    'log' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    
    • Logs appear in storage/logs/laravel.log.
  2. Verify File Paths

    • Use Storage::disk('public')->exists($path) to check if a file was saved.
    • Tip: Temporarily add dd($result) after upload to inspect the returned data.
  3. Common Errors

    • FileNotFoundException: Check if the file exists ($request->hasFile('field')).
    • InvalidArgumentException: Validate MIME types or disk configuration.

Extension Points

  1. Custom Storage Strategies Bind a custom storage adapter:

    $uploader->extend('custom', function () {
        return Storage::disk('custom_disk');
    });
    
    • Use in options:
      'disk' => 'custom'
      
  2. Event Listeners Listen for upload events (e.g., Atom\Uploader\Events\FileUploaded):

    // In EventServiceProvider
    protected $listen = [
        'Atom\Uploader\Events\FileUploaded' => [
            'App\Listeners\LogUpload',
        ],
    ];
    
  3. Middleware for Uploads Restrict uploads to authenticated users or roles:

    $uploader->middleware(function ($request, $next) {
        if (!$request->user()->can('upload-files')) {
            abort(403);
        }
        return $next($request);
    });
    
  4. Testing Uploads Use UploadTestCase or mock the Uploader facade:

    $this->partialMock(Uploader::class, function ($mock) {
        $mock->shouldReceive('upload')
             ->once()
             ->andReturn(['path' => 'test.jpg']);
    });
    
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.
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core