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

Laravel Imageup Laravel Package

qcod/laravel-imageup

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require qcod/laravel-imageup
    

    The package auto-registers; no manual provider setup is needed unless customizing config.

  2. Apply Trait to Model Add HasImageUploads to your Eloquent model and define $imageUploads:

    use QCod\ImageUp\HasImageUploads;
    
    class Product extends Model
    {
        use HasImageUploads;
    
        protected $imageUploads = [
            'image' => [
                'path' => 'products/{id}',
                'disk' => 'public',
                'width' => 800,
                'height' => 600,
                'crop' => true,
            ],
            'thumbnail' => [
                'path' => 'products/thumbs/{id}',
                'disk' => 'public',
                'width' => 200,
                'height' => 200,
                'crop' => false,
            ],
        ];
    }
    
  3. First Use Case Upload an image via a form with the field name matching the key in $imageUploads (e.g., image). The trait handles:

    • File validation (MIME type, size).
    • Automatic resizing/cropping.
    • Storage (local, S3, etc.).
    • Database record updates.

    Example request payload:

    {
        "name": "Example Product",
        "image": "base64_encoded_image_or_file_upload"
    }
    

Implementation Patterns

Core Workflow

  1. Form Handling Use the uploadImage method in your controller:

    public function store(Request $request)
    {
        $product = new Product();
        $product->name = $request->name;
        $product->uploadImage($request->file('image')); // Handles upload/resize
        $product->save();
    }
    
  2. Dynamic Uploads For dynamic field names (e.g., galleries), use the uploadImage method with a custom key:

    $product->uploadImage($request->file('gallery_image'), 'gallery_image');
    
  3. Batch Processing Process multiple images in a loop:

    foreach ($request->file('images') as $file) {
        $product->uploadImage($file, 'gallery_' . $loop->index);
    }
    

Integration Tips

  • Validation: Extend validation rules in validateImageUpload (override the trait method):

    public function validateImageUpload($field, $request)
    {
        $this->validate($request, [
            $field => 'required|image|mimes:jpeg,png|max:2048',
        ]);
    }
    
  • Custom Storage: Override getImageDisk to use different disks per field:

    protected function getImageDisk($field)
    {
        return $field === 'thumbnail' ? 's3' : 'public';
    }
    
  • Events: Listen for imageup.uploading, imageup.uploaded, or imageup.deleting events:

    event(new ImageUploading($model, $field, $file));
    
  • API Responses: Return URLs with getImageUrl:

    return response()->json([
        'url' => $product->getImageUrl('image'),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Field Name Mismatch

    • Ensure form field names match $imageUploads keys exactly. Case-sensitive.
    • Fix: Debug with dd($request->file()) to verify field names.
  2. Missing Disk Configuration

    • If images don’t save, check config/filesystems.php for the specified disk (e.g., public).
    • Fix: Publish config (php artisan vendor:publish --tag=imageup-config) and verify paths.
  3. Intervention Image Dependencies

    • Requires intervention/image. Install if missing:
      composer require intervention/image
      
  4. Crop Conflicts

    • If crop: true but no width/height are set, the package silently skips cropping.
    • Fix: Always define dimensions for cropped fields.
  5. Database Column Requirements

    • The trait expects columns for path and size (e.g., image_path, image_size).
    • Fix: Run migrations or update the model’s $fillable.

Debugging

  • Log Upload Events: Add a listener to debug:

    ImageUp::addListener('uploading', function ($event) {
        \Log::info('Uploading', $event->toArray());
    });
    
  • Check File Permissions: Ensure the storage path is writable:

    chmod -R 775 storage/app/public
    

Extension Points

  1. Custom Paths Dynamically generate paths using closures:

    'path' => function ($model) {
        return "products/{$model->category_slug}/{$model->id}";
    },
    
  2. Post-Processing Hook into imageup.uploaded to run additional logic (e.g., generate PDF thumbnails):

    ImageUp::addListener('uploaded', function ($event) {
        // $event->model, $event->field, $event->path
    });
    
  3. Fallback for Missing Fields Skip non-existent fields gracefully:

    if (method_exists($model, 'uploadImage')) {
        $model->uploadImage($file, $field);
    }
    
  4. Testing Mock the trait in tests:

    $model = new class extends Model {
        use HasImageUploads;
        protected $imageUploads = ['test' => ['path' => 'test']];
    };
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope