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

Fetch Laravel Package

nnjeim/fetch

View on GitHub
Deep Wiki
Context7

Getting Started

The upload method simplifies file handling in Laravel by providing a fluent interface for file uploads. To get started, install the package via Composer:

composer require vendor/package-name

Publish the config file (if applicable) and register the service provider in config/app.php. The first use case involves handling file uploads from a form:

use Vendor\PackageName\Facades\FileHandler;

public function uploadFile(Request $request)
{
    $file = $request->file('file_input');

    $result = FileHandler::upload($file)
        ->to('uploads/documents') // Destination path
        ->withName('custom_name.pdf') // Optional: Rename file
        ->withMetadata(['user_id' => auth()->id()]) // Optional: Attach metadata
        ->store();

    return response()->json($result);
}

Check the package's README.md for default configurations (e.g., disk settings, allowed MIME types) and the config/package-name.php file for customization options.


Implementation Patterns

1. Basic Upload Workflow

Use the upload() method for standard file handling:

FileHandler::upload($request->file('avatar'))
    ->to('avatars/users')
    ->store();

2. Chaining Methods

Leverage method chaining for complex uploads:

FileHandler::upload($file)
    ->validate(['max_size' => '2mb', 'mimes' => 'pdf,docx']) // Validate before upload
    ->to('documents/{year}/{month}', ['year' => date('Y'), 'month' => date('m')]) // Dynamic paths
    ->withName('invoice_{id}.pdf', ['id' => $invoice->id]) // Dynamic naming
    ->withMetadata(['client_id' => $client->id, 'type' => 'invoice'])
    ->store();

3. Integration with Laravel Storage

The package integrates seamlessly with Laravel's Storage facade. Specify a custom disk:

FileHandler::upload($file)
    ->to('backups')
    ->onDisk('s3') // Use S3 instead of default
    ->store();

4. Handling Multiple Files

Process arrays of files (e.g., from <input type="file" multiple>):

foreach ($request->file('files') as $file) {
    FileHandler::upload($file)
        ->to('uploads')
        ->store();
}

5. Post-Upload Actions

Trigger actions after upload (e.g., generate a thumbnail):

$upload = FileHandler::upload($file)
    ->to('images')
    ->store();

if ($upload->success()) {
    $this->generateThumbnail($upload->path);
}

Gotchas and Tips

Pitfalls

  1. Disk Configuration: Ensure the specified disk (e.g., s3, local) is properly configured in config/filesystems.php. Missing configurations will throw InvalidArgumentException.

  2. Validation Timing: Validation (e.g., validate()) runs before the upload. Skipping validation may lead to silent failures or security risks.

  3. Dynamic Paths: Use curly braces {} for dynamic path segments (e.g., to('users/{id}')). Unescaped values may cause path injection vulnerabilities.

  4. Metadata Serialization: Metadata is stored as JSON. Ensure all values are JSON-serializable (e.g., avoid passing objects directly).

Debugging Tips

  • Check Upload Logs: Enable debug mode (config('package-name.debug' = true)) to log upload attempts and failures to storage/logs/package-name.log.

  • Validate File Existence: Always check $file->isValid() before passing to FileHandler::upload() to avoid InvalidArgumentException.

  • Test with Small Files First: Start with small files (e.g., <100KB) to rule out disk/permission issues before testing large uploads.

Extension Points

  1. Custom Storage Drivers: Extend the package by adding support for new storage drivers via the StorageDriver interface:

    namespace Vendor\PackageName\Extensions;
    
    use Vendor\PackageName\Contracts\StorageDriver;
    
    class CustomDriver implements StorageDriver {
        public function store($file, $path, $metadata) { ... }
        public function url($path) { ... }
    }
    

    Register the driver in config/package-name.php under drivers.

  2. Pre/Post Upload Hooks: Bind events to extend upload behavior:

    FileHandler::upload($file)
        ->onBeforeUpload(function ($file) {
            // Pre-upload logic (e.g., resize image)
        })
        ->onAfterUpload(function ($result) {
            // Post-upload logic (e.g., send notification)
        })
        ->store();
    
  3. Override Default Config: Publish the config file (php artisan vendor:publish --tag=package-name-config) and customize:

    'default_disk' => 's3',
    'allowed_mimes' => ['pdf', 'jpg', 'png'],
    'max_size' => '10mb',
    
  4. Fallback for Missing Files: Handle cases where $request->file('key') returns null:

    $file = $request->file('avatar') ?? throw new \InvalidArgumentException('No file uploaded.');
    
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope