Download the PHP package devmahmoudmustafa/laravel-imagekit without Composer
On this page you can find all versions of the php package devmahmoudmustafa/laravel-imagekit. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download devmahmoudmustafa/laravel-imagekit
More information about devmahmoudmustafa/laravel-imagekit
Files in devmahmoudmustafa/laravel-imagekit
Package laravel-imagekit
Short Description Laravel ImageKit is a comprehensive image processing package for Laravel. It provides an easy-to-use service for validating, resizing, compressing, watermarking, and storing images, all with minimal configuration and maximum flexibility. Perfect for managing image assets in your Laravel applications.
License MIT
Informations about the package laravel-imagekit
Laravel ImageKit
Overview
The Laravel ImageKit package (v1.1.0) is a comprehensive image management tool that allows developers to handle various image operations such as uploading, resizing, watermarking, compressing, and storing images. This package integrates seamlessly with Laravel's Storage system, providing full support for local storage, cloud storage (S3, GCS, Azure), and maximum flexibility for diverse use cases.
Table of Contents
- Features
- Installation
- Configuration
- Quick Start
- Storage Disks
- Methods Reference
- Examples
- Events
- Error Handling
- Support and Contribution
Features
The ImageKit package provides a comprehensive set of features for image management:
📤 Image Upload & Validation
- Simple Image Upload - Upload images with minimal configuration
- Automatic Validation - Built-in validation for file types, size, and dimensions
- Multiple Format Support - Supports JPG, JPEG, PNG, and WebP formats
- File Size Validation - Configurable maximum file size limits
- Dimension Validation - Optional maximum width and height validation
- Extension Validation - Configurable allowed file extensions
🖼️ Image Resizing
- Single Size Resizing - Resize images to specific dimensions
- Multi-Size Resizing - Generate multiple sizes (thumbnail, small, medium, large, etc.) in one operation
- Aspect Ratio Control - Maintain or override aspect ratio when resizing
- Flexible Dimensions - Resize by width, height, or both
- Dynamic Sizing - Create custom size presets for your application
🗜️ Image Compression
- Quality Control - Adjustable compression quality (0-100)
- Dynamic Quality - Automatic quality calculation based on file size
- Format Optimization - Optimize images for web delivery
- Size Reduction - Reduce file sizes while maintaining visual quality
🎨 Watermarking
- Image Watermarking - Add watermarks to images with full control
- Uploaded Watermark Support - Use uploaded watermark images (not just file paths)
- Position Control - Place watermarks in 5 positions: top-left, top-right, bottom-left, bottom-right, center
- Opacity Control - Adjust watermark opacity (0-100)
- Offset Control - Fine-tune watermark position with pixel offsets
- Resizable Watermarks - Resize watermark images dynamically
- Multiple Watermark Sources - Use file paths or uploaded files
💾 Storage Management
- Multiple Storage Disks - Support for local, public, S3, GCS, Azure, and custom disks
- Dynamic Disk Switching - Switch between storage disks on the fly
- Custom Storage Paths - Configure custom paths for different image types
- Cloud Storage Ready - Full support for cloud storage services
- Storage Abstraction - Works with any Laravel storage driver
📁 File Naming Strategies
- Default Naming - Timestamp-based naming with random strings
- UUID Naming - Generate UUID-based filenames
- Hash Naming - Use hash-based naming for consistent files
- Timestamp Naming - Simple timestamp-based naming
- Custom Naming - Create your own naming strategy with callable functions
- Custom Names - Specify exact filenames when needed
🖼️ Gallery Operations
- Multiple Image Upload - Upload and process multiple images at once
- Batch Processing - Apply same transformations to multiple images
- Database Integration - Generate database-ready arrays with metadata
- Alt Text Support - Add alt text (single or per-image) to gallery images
- Foreign Key Support - Automatically link gallery images to database records
🗑️ Image Deletion
- Single Image Deletion - Delete individual images with optional size variants
- Gallery Deletion - Delete multiple images at once
- Multi-Size Cleanup - Automatically delete all size variants (small, medium, large, etc.)
- Safe Deletion - Validation and error handling for deletion operations
🔍 Image Retrieval
- Get Image Content - Retrieve raw image data from storage
- Display in Browser - Serve images directly to browsers with proper headers
- Download Images - Force download images with custom filenames
- Get Image URLs - Generate public URLs for images
- Get Image Paths - Retrieve full filesystem paths
- Check Existence - Verify if images exist before operations
- Temporary URLs - Generate temporary URLs for cloud storage (S3, etc.)
- Cache Control - Set cache headers for optimal performance
🎯 Fluent API
- Method Chaining - Chain multiple operations together
- Intuitive Methods - Clean, readable method names
- Multiple Aliases - Choose the method name that fits your style
- Type-Safe - Full type hints for better IDE support
📢 Events System
- ImageSaving Event - Fired before image is saved (with all processing options)
- ImageSaved Event - Fired after successful save (with image details)
- ImageDeleted Event - Fired after deletion attempt (with success status)
- Event Listeners - Full Laravel event system integration
- Custom Logic - Hook into image processing workflow
� Flexible Return Data
- Configurable Return Keys - Choose exactly what data to return after saving
- Single or Multiple Keys - Return string for one key, array for multiple
- Image Metadata - Get name, path, size, dimensions, URL, hash, and more
- Size Tracking - Track both original and final file sizes (in KB)
- Compression Analysis - Compare sizes before and after modifications
�🛠️ Configuration & Customization
- Comprehensive Config - Extensive configuration file for all settings
- Default Values - Sensible defaults that work out of the box
- Runtime Configuration - Override defaults at runtime
- Flexible Settings - Configure paths, sizes, quality, and more
✅ Error Handling
- Validation Errors - Clear, descriptive validation error messages
- Custom Exceptions - Specific exception types for different errors
- Graceful Failures - Proper error handling throughout
🔄 State Management
- Automatic Reset - State automatically resets after operations
- Manual Reset - Reset state manually when needed
- Fresh Instances - Create new instances to avoid state pollution
- Singleton Support - Works perfectly with singleton pattern
Installation
Step 1: Install the Package
Install the package using Composer:
Step 2: Publish the Configuration File
Publish the configuration file to customize default settings:
This command will create a imagekit.php file in the config directory.
Configuration
Default Configuration
The package comes with a comprehensive configuration file. Here's what you can configure:
Configuration Options Explained
disk
The storage disk to use. Can be any disk defined in config/filesystems.php:
'local'- Local storage'public'- Public storage's3'- Amazon S3'gcs'- Google Cloud Storage'azure'- Azure Blob Storage- Any custom disk
default_saved_path
Default path where images are saved (relative to disk root).
allowed_extensions
Allowed image file extensions for uploads.
max_file_size
Maximum file size in kilobytes. Set to null for no limit.
max_dimensions
Maximum image dimensions in pixels. Set to null for no limit.
naming_strategy
File naming strategy:
'default'-image_timestamp_random'uuid'- UUID v4 (requiresramsey/uuidpackage)'hash'- Hash-based name'timestamp'-timestamp_randomcallable- Custom function
enable_multi_size
Enable global multi-size resizing. When enabled, images are automatically resized to multiple sizes.
multi_size_dimensions
Define custom size dimensions for multi-size resizing.
dimensions
Default dimensions for single image resize.
aspectRatio
Whether to maintain aspect ratio when resizing (default: true).
compression_quality
Default compression quality (0-100). Set to null for dynamic quality based on file size.
enable_watermark
Enable watermark globally for all images.
watermark
Default watermark settings:
image- Path to watermark image (relative to disk or absolute path)position- Position:top-left,top-right,bottom-left,bottom-right,centeropacity- Opacity (0-100)x,y- Offset in pixelswidth- Watermark width in pixels (null = use original size)height- Watermark height in pixels (null = use original size)
watermark_storage_path
Default path where uploaded watermark images are saved (relative to disk root). This path is used when you pass an UploadedFile as the watermark image.
return_keys
Specify which data to return after saving an image. Available keys:
name- Image filenamepath- Directory pathfull_path- Full path (path + name)size- Final file size in KB (after all modifications)original_size- Original file size in KB (before modifications)url- Full URL to the imageextension- File extension (jpg, png, webp, etc.)mime_type- MIME type (image/jpeg, image/png, etc.)width- Image width in pixelsheight- Image height in pixelsdisk- Storage disk namehash- MD5 hash of the filecreated_at- Timestamp when saved
Behavior:
- If one key is specified → returns a
string(or appropriate type) - If multiple keys are specified → returns an
array
Default: ['name'] (returns only the image name as string)
Quick Start
Basic Usage
Using Cloud Storage
Storage Disks
The package fully supports Laravel's Storage abstraction, allowing you to use any storage driver.
Setting Disk
Default Storage Disks
Using the public Disk
When using the public disk (default), images are saved in storage/app/public/ directory.
Important: To access images directly from URLs (e.g., http://your-domain.com/storage/uploads/images/image.jpg), you must create a symbolic link by running:
This command creates a symbolic link from public/storage to storage/app/public, making stored files publicly accessible.
Without running this command, you won't be able to access images via direct URLs, and you'll need to use the package's response() or getImageUrl() methods to serve images.
Example:
Creating Custom Storage Disks
You can create any custom disk configuration in config/filesystems.php. The package will work with any disk you define.
Example: Save Images Directly in public/ Directory
If you want to save images directly in the public/ folder (instead of storage/app/public/), create a custom disk:
-
Add the disk configuration in
config/filesystems.php: - Use the custom disk in your code:
Note: Saving directly to public/ folder doesn't require storage:link command, but it's generally not recommended for production as files in public/ are directly accessible and harder to manage.
Example: Custom Local Disk
You can create disks pointing to any directory:
Then use them:
Cloud Storage Setup
Amazon S3
-
Configure in
config/filesystems.php: - Use in code:
Google Cloud Storage
Similar setup, use 'gcs' as disk name.
Azure Blob Storage
Similar setup, use 'azure' as disk name.
Methods Reference
Image Methods
setImage($image) / image($image)
Set the image file to be processed.
Parameters:
$image-Illuminate\Http\UploadedFile
Example:
setImages(array $images) / images(array $images)
Set multiple images for gallery processing.
Example:
Path & Name Methods
setImagePath($path) / path($path) / saveTo($path)
Set the path where images will be saved (relative to disk root).
Example:
setImageName($name) / name($name)
Set a custom name for the image file.
Example:
setExtension($extension) / extension($extension)
Set a custom file extension.
Example:
Resize Methods
setDimensions($width, $height) / resize($width, $height) / dimensions($width, $height)
Resize image to specific dimensions.
Parameters:
$width- Width in pixels (null to maintain aspect ratio)$height- Height in pixels (null to maintain aspect ratio)
Example:
setMultiSizeOptions($sizes) / sizes($sizes)
Resize image to multiple sizes.
Parameters:
$sizes- Array of size names (must exist inmulti_size_dimensionsconfig)
Example:
Compression Methods
compressImage($compress, $quality) / compress($compress, $quality)
Compress the image.
Parameters:
$compress- Enable/disable compression (default:true)$quality- Quality 0-100 (null = dynamic based on file size)
Example:
Watermark Methods
setWatermark(...) / watermark(...)
Apply watermark to the image.
Parameters:
$imagePathOrFile- Path to watermark image (relative to disk or absolute) ORUploadedFileinstance$position- Position:top-left,top-right,bottom-left,bottom-right,center$opacity- Opacity 0-100$offset- Array withxandykeys$x- Horizontal offset$y- Vertical offset$width- Watermark width in pixels (null = use original size)$height- Watermark height in pixels (null = use original size)
Example:
Storage Methods
setDisk($disk)
Set the storage disk to use.
Parameters:
$disk- Disk name (e.g.,'public','s3','gcs')
Example:
getDisk()
Get the current storage disk being used.
Returns: string - Current disk name
Example:
Save Methods
saveImage() / save()
Save the image after applying all modifications.
Returns: string|array - Based on return_keys config:
- Single key →
string(or appropriate type) - Multiple keys →
arraywith requested data
Example:
saveGallery($imageColumnName, $fkColumnName, $fkId, $altText)
Save multiple images as a gallery.
Parameters:
$imageColumnName- Database column name for image filename (optional)$fkColumnName- Foreign key column name (optional)$fkId- Foreign key value (optional)$altText- Alt text - can be string or array (optional)
Returns: array - Array of results based on return_keys config:
- Single key without metadata → array of strings
- Multiple keys or with metadata → array of arrays
Example:
Utility Methods
make()
Create a fresh instance of the service (useful for avoiding state pollution).
Example:
reset()
Reset the service to initial state.
Example:
Delete Methods
deleteImage($imageName, $path, $sizes)
Delete a single image.
Parameters:
$imageName- Image filename (can include full path if$pathis null)$path- Path relative to disk root (optional). If null or empty, path will be extracted from$imageName$sizes- Array of sizes to delete (optional)
Returns: bool
Throws: InvalidArgumentException if image is in root directory when path is extracted from imageName
Examples:
deleteGallery($imagesNames, $path, $sizes)
Delete multiple images.
Parameters:
$imagesNames- Array of image filenames (can include full paths if$pathis null)$path- Path relative to disk root (optional). If null or empty, path will be extracted from each$imageName$sizes- Array of sizes to delete (optional)
Returns: int - Number of successfully deleted images
Throws: InvalidArgumentException if any image is in root directory when path is extracted from imageName
Examples:
Examples
Example 1: Basic Upload
Example 2: Resize and Compress
Example 3: Multi-Size with Watermark
Example 3.1: Watermark with UploadedFile
Example 3.2: Watermark with Dimensions
Example 4: Using Cloud Storage (S3)
Example 5: Custom File Naming
Example 6: Gallery with Database Integration
Example 7: Fluent API Chain
Example 8: Dynamic Disk Switching
Example 8.1: Custom Return Keys
Example 8.2: Get All Image Metadata
Example 8.3: Gallery with Return Keys
Example 9: Display Image in Browser
Example 10: Download Image
Example 11: Get Image URL
Example 12: Temporary URL (Cloud Storage)
Image Retrieval Methods
All image retrieval methods support an optional $disk parameter. If not provided, the current disk from config or the last set disk will be used.
Retrieval Methods
getImage($path, $disk)
Get image content from storage.
Parameters:
$path- Relative path on the storage disk$disk- Optional disk name (uses config disk if not provided)
Returns: string|null - Image content or null if file doesn't exist
Example:
response($path, $disk, $options)
Get HTTP response for displaying image in browser.
Parameters:
$path- Relative path on the storage disk$disk- Optional disk name$options- Array of options:contentType- Custom MIME type (auto-detected if not provided)headers- Custom headers arraycache- Cache control (false = no cache, or number = max-age in seconds)disposition- 'inline' (default) or 'attachment'filename- Custom filename for Content-Disposition
Returns: \Illuminate\Http\Response
Example:
download($path, $name, $disk, $options)
Get download response for image.
Parameters:
$path- Relative path on the storage disk$name- Optional download filename$disk- Optional disk name$options- Additional options (headers, etc.)
Returns: \Symfony\Component\HttpFoundation\StreamedResponse
Example:
getImageUrl($path, $disk)
Get the full URL for an image.
Parameters:
$path- Relative path on the storage disk$disk- Optional disk name
Returns: string - Full URL
Example:
getImagePath($path, $disk)
Get the full filesystem path for an image (for local disk operations).
Parameters:
$path- Relative path on the storage disk$disk- Optional disk name
Returns: string - Full filesystem path
Example:
imageExists($path, $disk)
Check if image file exists.
Parameters:
$path- Relative path on the storage disk$disk- Optional disk name
Returns: bool
Example:
temporaryUrl($path, $expiration, $disk, $options)
Get temporary URL for image (useful for cloud storage like S3).
Parameters:
$path- Relative path on the storage disk$expiration- Expiration time (DateTimeInterface, DateInterval, or int seconds)$disk- Optional disk name$options- Additional options
Returns: string - Temporary URL
Example:
Events
The package fires events at key points during image processing. See EVENTS.md for complete documentation.
Available Events
ImageSaving- Fired before image is savedImageSaved- Fired after image is successfully savedImageDeleted- Fired after image deletion attempt
Example: Listening to Events
Error Handling
The package throws InvalidArgumentException for validation errors. Always use try-catch blocks:
Common Errors
- Invalid file type - File extension not in
allowed_extensions - File too large - Exceeds
max_file_sizelimit - Image too large - Exceeds
max_dimensionslimit - Watermark not found - Watermark image file doesn't exist
- Invalid dimensions - Invalid width/height values
Support and Contribution
For support or to contribute to this package, visit the GitHub repository.
License
This package is open-sourced software licensed under the MIT license.
All versions of laravel-imagekit with dependencies
illuminate/support Version ^9.0|^10.0|^11.0|^12.0
illuminate/filesystem Version ^9.0|^10.0|^11.0|^12.0
intervention/image Version ^2.7