Laravel ImageUp

repository·master·Indexed 21 days ago

https://github.com/qcod/laravel-imageup

A Laravel trait that automates the uploading, resizing, cropping, and management of images and files within Eloquent models. It provides the HasImageUploads trait to handle automatic uploads via the Model::saved() event, supports granular field configuration for dimensions and storage disks, and includes manual upload and manipulation methods such as resizeImage and cropTo.

Tokens
3.2K
Snippets
12
Records
12
Agent score
23%

What's inside laravel-imageup

  1. Use image hooks for customization

    master

    Hooks allow you to run logic before or after an image is saved. You can define hooks using either a Class or a Callback.

    Class-based Hooks

    Specify a class name in your $imageFields definition. The class must implement a handle($image) method, where $image is an instance of Intervention Image. These are resolved via the Laravel IoC container.

    Callback Hooks

    Pass an anonymous function directly into the field options.

    Hook Types

    • before_save: Called before the image is written to disk. Changes made to the $image instance here will be applied to the final file.
    • after_save: Called after the image is saved to disk. Useful for post-processing like watermarking.

    Note: If you have defined width or height in your field options, the $image instance passed to the hook will already be resized.

    // Class-based hook
    class BlurFilter {
        public function handle($image) {
            $image->blur(10);
        }
    }
    
    // Definition in model
    protected static $imageFields = [
        'avatar' => [
            'before_save' => BlurFilter::class,
        ],
    ];
    
    // Callback-based hook
    $user->setImagesField([
        'avatar' => [
            'before_save' => function($image) {
                $image->blur(10);
            },
        ]
    ]);
  2. Publish the ImageUp configuration file

    master

    To customize global settings, publish the configuration file to config/imageup.php using the following artisan command:

    php artisan vendor:publish --provider="QCod\ImageUp\ImageUpServiceProvider" --tag="config"
  3. Get started with HasImageUploads trait

    master

    To enable automatic image handling, add the HasImageUploads trait to your Eloquent model and define the $imageFields property. The package hooks into the Model::saved() event to handle uploads, database updates, and old file deletion.

    Note: Database columns for image fields must be of type VARCHAR to store the file path. Ensure you have run php artisan storage:link to access files via the public disk.

    <?php
    namespace App;
    
    use QCod\ImageUp\HasImageUploads;
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model {
        use HasImageUploads;
        
        // Mark columns as image fields
        protected static $imageFields = [
            'cover', 'avatar'
        ];
    }
  4. Configure Laravel ImageUp settings

    master

    The package configuration file controls global behavior for uploads, storage, and deletions. Key options include:

    • upload_disk: The default Laravel storage disk (e.g., public).
    • upload_directory: The directory within the disk where files are stored.
    • auto_upload_images: Whether to automatically upload files from the request if field names match (default: true).
    • auto_delete_images: Whether to automatically delete files from disk when the database record is deleted (default: true).
    • resize_image_quality: The default JPEG/WebP quality for resized images.
    return [
        'upload_disk' => 'public',
        'upload_directory' => 'uploads',
        'auto_upload_images' => true,
        'auto_delete_images' => true,
        'resize_image_quality' => 80
    ];
  5. Customize the uploaded filename

    master

    By default, files are saved using $file->hashName(). To use a custom naming convention, implement a method in your model following the pattern {fieldName}UploadFilePath.

    Important: The method must return only the relative path from the disk. The method receives the uploaded $file object as an argument.

    class User extends Model {
        use HasImageUploads;
        
        protected static $imageFields = ['cover', 'avatar'];
        
        // Override cover file name
        protected function coverUploadFilePath($file) {
            // Example: saves as 'uploads/1-cover-image.jpg'
            return $this->id . '-cover-image.jpg';
        }
    
        // Example using original filename
        protected function avatarUploadFilePath($file) {
            return $this->id . '-' . $file->getClientOriginalName();
        }
    }
  6. Manually upload images and files

    master

    If you have disabled auto-upload (via protected $autoUploadImages = false;, $model->disableAutoUpload(), or field-specific settings), you can manually handle uploads using the following methods:

    • $model->uploadImage($imageFile, $field = null): Uploads an image to the specified field. If $field is null, it uploads to the first image option defined in the model.
    • $model->uploadFile($docFile, $field = null): Uploads a file to the specified field.

    Important: If auto-upload is enabled, manual uploads may be overwritten by the auto-upload process during model save.

    $user = User::findOrFail($id);
    $user->uploadImage(request()->file('cover'), 'cover');
    $user->uploadFile(request()->file('resume'), 'resume');
  7. Retrieve image and file URLs or tags

    master

    To display uploaded assets in your application:

    • $model->imageUrl($field): Returns the URL string for the image in the specified field.
    • $model->fileUrl($field): Returns the URL string for the file in the specified field.
    • $model->imageTag($field, $attribute = ''): Returns a complete HTML <img> tag. You can pass an optional $attribute string (e.g., CSS classes) to the tag.
    // Get URL
    <img src="{{ $user->imageUrl('cover') }}" alt="" />
    
    // Get HTML Tag with classes
    {!! $model->imageTag('avatar', 'class="float-left mr-3"') !!}
  8. Dynamically configure image and file fields

    master

    You can override the image or file fields defined on your model at runtime using these methods:

    • $model->setImagesField($fieldsOptions): Replaces the image fields configuration.
    • $model->setFilesField($fieldsOptions): Replaces the file fields configuration.

    Example configuration options include width, height, crop, and path.

    $user = User::findOrFail($id);
    
    $fieldOptions = [
        'cover' => [ 'width' => 1000 ],
        'avatar' => [ 'width' => 120, 'crop' => true ],    
    ];
    $user->setImagesField($fieldOptions);
    
    $fileFieldOption = [
        'resume' => ['path' => 'resumes']
    ];
    $user->setFilesField($fileFieldOption);
  9. Resize and crop images manually

    master

    You can perform image manipulation outside of the automatic upload flow:

    • $model->resizeImage($imageFile, $fieldOptions): Resizes an existing image file or an uploaded file using provided options (e.g., width, crop). Returns the Intervention Image instance.
    • $model->cropTo($x, $y)->resizeImage($imageFile, $field = null): Sets specific X and Y coordinates for cropping (useful for frontend cropping libraries) before resizing or uploading.
    // Resize an existing file
    $image = $user->resizeImage('/images/some-big-image.jpg', [ 'width' => 120, 'crop' => true ]);
    
    // Crop and upload using coordinates from request
    $coords = request()->only(['crop_x', 'crop_y']);
    $user->cropTo($coords)->uploadImage(request()->file('cover'), 'avatar');
  10. Configure Upload Field options for images and files

    master

    You can provide granular configuration for each field within $imageFields (for images) or $fileFields (for general files).

    Image Field Options ($imageFields)

    • width: Resize width after upload.
    • height: Resize height after upload.
    • crop: Set to true to crop to the given dimensions. Can accept [x, y] coordinates.
    • disk: The storage disk to use (overrides global config).
    • path: The folder path on the disk (overrides global config).
    • placeholder: Path to a placeholder image if the field is empty.
    • rules: Validation rules for the upload.
    • auto_upload: Boolean to override global auto-upload setting.
    • file_input: The name of the file in the request (defaults to field name).
    • update_database: Boolean; if false, the field won't be updated in the DB.
    • before_save: Class name of a hook triggered before saving.
    • after_save: Class name of a hook triggered after saving.

    File Field Options ($fileFields)

    Used for non-image files (e.g., PDFs, DOCX). Supports similar options like disk, path, rules, auto_upload, file_input, before_save, and after_save.

    class User extends Model {
        use HasImageUploads;
        
        protected $imagesUploadDisk = 'local';
        protected $imagesUploadPath = 'uploads';
        protected $autoUploadImages = true;
        
        protected static $imageFields = [
            'avatar' => [
                'width' => 200,
                'height' => 100,
                'crop' => true,
                'disk' => 'public',
                'path' => 'avatars',
                'placeholder' => '/images/avatar-placeholder.svg',
                'rules' => 'image|max:2000',
                'auto_upload' => false,
                'file_input' => 'photo',
                'update_database' => false,
                'before_save' => BlurFilter::class,
                'after_save' => CreateWatermarkImage::class
            ]
        ];
    
        protected static $fileFields = [
            'resume' => [
                'disk' => 'public',
                'path' => 'docs',
                'rules' => 'mimes:doc,pdf,docx|max:1000',
                'auto_upload' => false,
                'file_input' => 'cv',
                'before_save' => HookForBeforeSave::class,
                'after_save' => HookForAfterSave::class
            ]
        ];
    }