Download the PHP package rayzenai/file-manager without Composer
On this page you can find all versions of the php package rayzenai/file-manager. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download rayzenai/file-manager
More information about rayzenai/file-manager
Files in rayzenai/file-manager
Package file-manager
Short Description This is FileHandling package to be used with FilamentPHP/Laravel.
License MIT
Homepage https://github.com/rayzenai/file-manager
Informations about the package file-manager
Laravel File Manager for Filament
A comprehensive Laravel package for Filament v4 that provides advanced file management with automatic image resizing, compression, media metadata tracking, and seamless S3 integration. Built for high-performance applications handling large volumes of media content.
This package is developed and maintained by Kiran Timsina and RayzenTech.
Key Features
Core Features
- 🖼️ Automatic Image Resizing - Generate multiple sizes automatically on upload
- 🗜️ Smart Compression - WebP/AVIF conversion with configurable quality settings
- 🎬 Video Compression - FFmpeg-based video optimization with WebM/MP4 output, H.264/H.265/VP9 codecs
- 📊 Media Metadata Tracking - Track file sizes, dimensions, and compression stats
- ☁️ S3 Integration - Seamless AWS S3 storage with CDN support
- ⚡ Cache Control Headers - Configurable browser/CDN caching for optimal performance
- 📏 Smart File Size Limits - Automatic detection and different limits for images (8MB), videos (100MB), and documents (20MB)
- 🛠️ Artisan Commands - CLI tools for populating metadata with progress tracking
- 📁 Media Metadata Resource - Dedicated admin page for managing media with bulk operations
- 🖼️ Image Processor Page - Interactive tool for testing compression and processing settings
Advanced Processing
- 🎨 Flexible Driver System - Choose between GD Library or Imagick
- 🖼️ Interactive Processor - Test and process images directly in admin panel
- 📈 Bulk Operations - Process multiple files with detailed progress tracking
- ⚙️ Queue Processing - Asynchronous processing for large files
Developer Experience
- 🎨 Custom Filament Components - MediaUpload and S3Image components
- 🔍 Advanced Resource Management - Built-in media metadata interface with bulk actions
- 🚀 Performance Optimized - Queue-based processing with chunked operations
- 🔧 Highly Configurable - Extensive configuration with environment variables
- 📝 Comprehensive CLI - Powerful artisan commands with progress tracking
About the Developers
Kiran Timsina is a full-stack developer specializing in Laravel and Filament applications. Connect on GitHub.
RayzenTech is a tech startup based in Nepal focused on creating smart business solutions. We specialize in automating complex processes and making them simple, from business automation to robotic process automation. Learn more at RayzenTech.
Requirements
- PHP 8.1+
- Laravel 10.0+
- Filament 4.0+
- AWS S3 configured (or S3-compatible storage)
- FFmpeg (optional, required for video compression)
Storage Configuration
This package works with both AWS S3 and Cloudflare R2. Choose one of the following configurations:
Option 1: Using AWS S3
1. Configure .env file:
2. Configure config/filesystems.php:
3. Configure config/livewire.php (if using Livewire uploads):
Option 2: Using Cloudflare R2
1. Configure .env file:
2. Configure config/filesystems.php:
3. Configure config/livewire.php (if using Livewire uploads):
Option 3: Using S3 Disk with R2 (Simplified)
If you prefer to use the standard S3 configuration with R2, you can configure R2 using the AWS environment variables:
Configure .env file:
This approach uses the existing s3 disk configuration in filesystems.php without creating a separate r2 disk.
Storage Driver Comparison
| Feature | AWS S3 | Cloudflare R2 |
|---|---|---|
| Storage Cost | ~$0.023/GB | $0.015/GB |
| Egress Fees | $0.09/GB after 1GB | $0 (free egress) |
| API Compatibility | Native S3 API | S3-compatible API |
| Region Config | Specific region (e.g., us-east-1) | Always use 'auto' |
| Best For | AWS ecosystem integration | Cost-effective, high bandwidth usage |
Installation
-
Install via Composer:
-
Publish the configuration:
-
Publish and run migrations (for media metadata):
-
Configure storage and environment variables:
See the Storage Configuration section above for detailed setup instructions for AWS S3 or Cloudflare R2.
Additional configuration options for
.env: - Register the plugin in your Filament panel provider:
Configuration
The configuration file config/file-manager.php allows you to customize:
Usage in Models
Using the HasMultimedia Trait
The HasMultimedia trait automatically handles media file processing including image resizing, video compression, and document management:
Key Features:
- Automatically generates multiple sizes when images are saved
- Handles both single images and arrays of images
- Smart diffing - only resizes truly new images
- Automatic cleanup of old media files when replaced
- Queue-based processing for better performance
- Video compression with configurable codecs and quality
- Document file support without unwanted processing
- Automatic file type detection based on field configuration
Usage in Filament Resources
SEO Title Support
The package includes built-in SEO title functionality for better search engine optimization of media files:
Configuration:
Control which models receive SEO titles in config/file-manager.php:
MediaUpload Component
The MediaUpload component extends Filament's FileUpload with automatic compression and metadata tracking:
Available Methods:
Image Methods:
quality(int $quality): Set compression quality (1-95, default: from config)format(string $format): Set output format ('webp', 'jpeg', 'jpg', 'png', 'avif', 'original')toWebp(): Convert images to WebP formattoAvif(): Convert images to AVIF format (requires Imagick, not available with GD)keepOriginalFormat(): Compress but keep the original file formatuploadOriginal(): Skip ALL processing - no compression, no resizing, no format conversiontrackMetadata(): Enable/disable metadata trackingresize(): Enable Filament's built-in resizing (opposite of uploadOriginal)
Video Methods:
toWebm(): Complete WebM setup with optimal settings (1000kbps, 1080p, CRF 30)toMp4(): Complete MP4 setup with optimal settings (1500kbps, 1080p, CRF 23)compressVideo(): Enable video compressionvideoFormat('webm'|'mp4'): Set video output formatvideoBitrate(int): Set video bitrate in kbpsvideoMaxDimensions(width, height): Set maximum video dimensionsvideoPreset('ultrafast'|'fast'|'medium'|'slow'|'veryslow'): Encoding speed/quality trade-offvideoCrf(int): Set quality (0-63, lower = better)videoAsync(bool): Enable async processing (recommended)
Important Notes:
- Compression: Images are automatically compressed when enabled in config (unless
uploadOriginal()is called) - Format Control: Use
toWebp(),toAvif(), orformat()to override config format - Upload Original: Call
uploadOriginal()to skip ALL processing and upload file exactly as-is
Features:
- Smart compression with configurable output format (WebP/JPEG/PNG/AVIF)
- Metadata tracking with compression stats
- Supports both images and videos
- SEO-friendly file naming
- Choice between GD Library and Imagick drivers
MediaModalColumn and MediaUrlColumn
Display images in tables with different interaction styles:
MediaModalColumn
Display images with modal preview and optional editing capabilities:
MediaUrlColumn
Display images that link to a dedicated media page:
Common Methods (both components):
thumbnailSize(): Set thumbnail size ('icon', 'small', 'medium', 'large', etc.)label(): Column labelrelationship(): Name of the Eloquent relationship (for HasMany, HasOne, BelongsTo)showMetadata(): Show file metadata in tooltipviewCountField(): Field to track view counts
MediaModalColumn specific methods:
modalSize(): Size for modal preview imagesheading(): Modal heading (closure or string)allowEdit(): Enable editing images in modalmultiple(): Handle multiple imagesdownloadable(): Allow image downloadspreviewable(): Enable image previewuploadOriginal(): Upload file as-is without any processing (default: false)
MediaUrlColumn specific methods:
openInNewTab(): Open media page in new tab (default: true)
Features:
- Direct field access: Works with model attributes directly
- Relationship support: Access images through Eloquent relationships
- Dot notation: Legacy support for nested relationships
- Modal editing: View and replace images through modal interface
- Multiple images: Handles both single and multiple image fields
- Smart loading: Automatically loads relationships to prevent N+1 queries
- Metadata display: Optional file size and type information
Relationship Support (v4.3+):
The relationship parameter allows you to display and manage images from related models:
This will:
- Display all attachment images in the table column
- Allow viewing all images in a modal
- Enable uploading new images that will replace existing attachments
- Handle HasMany, HasOne, and BelongsTo relationships automatically
Default Sizes
You can configure default sizes for MediaColumn components in your configuration:
Or via environment variables:
Available size configurations:
default_thumbnail_size: Used for thumbnail displays in table columns (default:'icon')default_card_size: Used for larger preview displays like modals (default:'card')
Individual columns can still override these defaults (limited to thumbnail size only):
S3Image Column
Display images in tables with modal preview:
Media Metadata Management
The package includes a powerful Filament resource for comprehensive media management.
Dashboard Features
Navigation & Monitoring
- Smart Navigation Badge: Real-time count of large files (>500KB)
- 🔵 Info: 1-50 large files
- 🟡 Warning: 51-100 large files
- 🔴 Danger: 100+ large files
- Automatic cache refresh every 5 minutes
File Management
- Comprehensive file listing with:
- Model type and ID
- Field name
- File size with human-readable format
- Image dimensions (width × height)
- MIME type with color-coded badges
- Creation and update timestamps
Advanced Filtering
- Quick Filters:
- Inefficient Images (>0.35 bytes per pixel, >10KB) - Smart filter for images that would benefit from WebP compression
- Large Files (>500KB)
- Very Large Files (>2MB)
- Model Type Filter: Filter by specific models
- File Type Filter: Filter by MIME type
- Search: Find files by name or path
Individual File Actions
- Open in Panel: Navigate directly to the parent resource
- Resize: Generate all configured size variations
- Compress: Apply custom compression settings
- Rename: Update file names in database
- Delete Resized: Remove all size variations
Bulk Operations
Bulk Compress
- Select multiple images for compression
- Choose output format (WebP, AVIF, JPEG, PNG)
- Set compression quality (50-100%)
- Option to replace originals
- Detailed progress reporting
Bulk Resize
- Generate all size variations for selected images
- Queue-based processing for performance
- Progress notifications
Bulk Delete Resized
- Remove all resized versions for selected images
- Confirmation dialog with warnings
- Batch processing with result summary
Image Processor Page
The MediaMetadata resource includes a dedicated Image Processor page - a powerful tool for testing and optimizing your image processing pipeline.
Features:
Upload & Process
- Drag-and-drop or click to upload images up to 10MB
- Support for JPEG, PNG, WebP, and AVIF formats
- Real-time preview of uploaded images
Processing Options
- Format Selection: Convert between WebP, JPEG, PNG, and AVIF
- Quality Control: Adjust compression from 50% to 100%
- Resizing: Set custom dimensions with multiple resize modes
Compression Drivers
- GD Library: Fast, built-in PHP processing with lower memory usage
- Imagick: Better quality and more features using ImageMagick
Results & Analytics
- Side-by-side comparison of original vs processed
- Detailed statistics:
- Original and compressed file sizes
- Space saved (KB and percentage)
- Final dimensions
- Processing method used
- Download processed images directly
Use Cases:
- Test compression settings before applying to production
- Optimize images for specific use cases
- Compare processing drivers (GD vs Imagick)
- Evaluate different output formats (WebP, AVIF, JPEG, PNG)
- Generate samples for documentation
Service Methods
Using the FileManager Facade
Image Compression Service
Compression Drivers:
- GD Library (
driver: 'gd'): Built-in PHP image processing using GD extension. Fast, lower memory usage, suitable for most use cases. Supports WebP, JPEG, and PNG formats. - Imagick (
driver: 'imagick'): Uses ImageMagick extension for image processing. Better quality, more features, supports additional formats like AVIF. Requires ImageMagick to be installed on the server.
Video Compression Service
The package now includes comprehensive video compression capabilities using FFmpeg to convert and optimize video files.
Prerequisites:
Configuration:
Using Video Compression in Forms:
Convenience Helper Methods:
The package provides two convenient helper methods that configure all video settings with a single call:
toWebm() - Optimized for web delivery with WebM format:
- Accepts common video formats (MP4, WebM, QuickTime, M4V)
- Outputs WebM format with VP9 codec
- 1000 kbps bitrate for balanced quality/size
- 1920x1080 max dimensions (Full HD)
- Medium preset for optimal encoding speed
- CRF 30 for good compression
- Async processing enabled
toMp4() - Universal compatibility with MP4 format:
- Accepts common video formats (MP4, WebM, QuickTime, M4V)
- Outputs MP4 format with H.264 codec
- 1500 kbps bitrate for better quality
- 1920x1080 max dimensions (Full HD)
- Medium preset for optimal encoding speed
- CRF 23 for higher quality
- Async processing enabled
Programmatic Video Compression:
Async Video Processing with Queue:
Bulk Video Compression Command:
Video Format Recommendations:
| Format | Video Codec | Audio Codec | Use Case | Pros | Cons |
|---|---|---|---|---|---|
| WebM | VP9 | Opus | Modern web | Better compression, open source | Limited browser support (no Safari) |
| WebM | VP8 | Vorbis | Legacy web | Wider browser support | Larger files than VP9 |
| MP4 | H.264 | AAC | Universal | Maximum compatibility | Larger files, licensing |
| MP4 | H.265/HEVC | AAC | High quality | 50% smaller than H.264 | Limited browser support |
Preset Performance Guide:
- ultrafast: Fastest encoding, largest files, lowest quality
- fast: Good balance for real-time processing
- medium: Default, balanced quality and speed
- slow: Better quality, smaller files, longer processing
- veryslow: Best compression, smallest files, very slow
CRF (Constant Rate Factor) Guidelines:
- 0-17: Visually lossless (very large files)
- 18-23: High quality (recommended for high-quality content)
- 24-30: Good quality (recommended for web)
- 31-40: Acceptable quality (smaller files)
- 41-63: Low quality (very small files)
Queue Jobs
The package uses queued jobs for better performance. Jobs are dispatched to configurable queues.
Queue Configuration
Configure queue names in config/file-manager.php:
Running Queue Workers
If using Laravel Horizon (recommended for production): You might have to configure horizon to use supervisors as your requirements. Check horizon's docs for more info on how to configure queues.
If NOT using Horizon, you must explicitly specify the queues:
⚠️ Important: If you're using a database queue driver without Horizon and don't specify the queue names, jobs on non-default queues will not be processed!
Available Jobs
ResizeImages- Generate multiple sizes for uploaded images (usesqueue.images)DeleteMedia- Clean up all media files and their sizes (usesqueue.delete)PopulateMediaMetadataJob- Populate media metadata for existing media filesCompressVideoJob- Asynchronously compress and optimize video files (usesqueue.videos)
Artisan Commands
The package provides several powerful Artisan commands for managing your media files and metadata:
| Command | Purpose | Key Features |
|---|---|---|
file-manager:manage-sizes |
Add/remove image sizes for all media | Config checking, batch processing, dry run |
file-manager:refresh-all |
Queue refresh jobs for all media | Metadata sync, dimension updates, batch jobs |
file-manager:populate-seo-titles |
Generate SEO titles for media files | Dry run, model filtering, chunked processing |
file-manager:update-seo-titles |
Update SEO titles when models change | Model-specific updates, automatic tracking |
file-manager:populate-metadata |
Create metadata for existing images | Auto-fixes MIME types, progress tracking |
file-manager:remove-duplicates |
Remove duplicate metadata records | Safe cleanup, dry run preview |
file-manager:update-cache-headers |
Add cache headers to existing S3 images | Directory-specific, progress tracking |
file-manager:cleanup-old-media |
Delete old media files from storage | Age threshold, PrunableMedia trait, dry run |
Manage Image Sizes
Add or remove image sizes for all media files in the media_metadata table. This command is useful when you need to add a new size to your configuration or clean up unused sizes.
Adding a New Size
Removing an Existing Size
Key Features
- Safe Operations: Dry-run mode lets you preview changes before executing
- Progress Tracking: Real-time progress bar shows current status
- Batch Processing: Configurable chunk sizes for memory efficiency
- Error Handling: Detailed error reporting for failed operations
- S3 Integration: Automatically handles S3 file creation and deletion
- Format Support: Uses configured compression format (WebP, JPEG, PNG, AVIF)
Important Notes
- Configuration First Approach: The command enforces configuration updates before operations:
- Adding: Blocks execution if size not in config, requires you to add it first
- Removing: Blocks execution if size still in config, requires you to remove it first
- This prevents orphaned files and ensures configuration consistency
-
Two-Step Process:
- Update your configuration in
config/file-manager.php - Run the command to process the files
- Update your configuration in
- Storage Requirements: Adding sizes will increase storage usage as new files are created
- Processing Time: Large datasets may take considerable time to process
- File Cleanup: Removing sizes permanently deletes the associated image files
Example Output
Blocked when size not in config:
Success after adding to config:
Refresh All Media
Queue refresh jobs to update metadata for all media files. This command checks file metadata, dimensions, and synchronizes database records with actual file states in S3 storage.
What It Checks
- File Size Changes: Updates file_size if different from S3
- MIME Type Changes: Updates mime_type based on current file
- Image Dimensions: Recalculates width/height for image files
- Model References: Verifies parent models still reference the file
Key Features
- Queued Processing: Uses background jobs to avoid timeouts
- Progress Tracking: Real-time notifications every 10 completed jobs
- Batch Processing: Configurable chunk sizes for memory efficiency
- Safe Operations: Dry-run mode to preview changes
- Error Handling: Detailed logging and retry logic
- Non-Destructive: Only updates metadata, doesn't modify files
Example Output
GUI Alternative
You can also use the "Refresh All (Queued)" bulk action in the MediaMetadata admin panel to refresh selected records through the UI.
Populate SEO Titles
Generate SEO-optimized titles for existing media files based on their parent model data:
Features:
- Intelligently extracts titles from parent model fields (meta_title, seo_title, name, title, etc.)
- Removes special characters from beginning/end of titles
- Respects configuration for enabled/excluded models
- Processes large datasets efficiently with chunked operations
- Shows detailed breakdown by model type
Update SEO Titles
Update SEO titles when parent model data changes:
Automatic Updates with HasMultimedia Trait
The HasMultimedia trait now includes automatic SEO title updates. Simply define which field to use for SEO titles in your model:
The HasMultimedia trait now provides:
- Automatic image resizing for configured sizes
- Video compression with queue processing
- Media metadata tracking for all file types
- Automatic SEO title updates when the field returned by
seoTitleField()changes - Smart file type detection and processing based on field configuration
How SEO Titles Work:
- Opt-in system: Only models with a
seoTitleField()method will have SEO titles - No configuration needed: The presence of the method indicates the model wants SEO titles
- Null is fine: If the specified field is null/empty, the SEO title will be null
- Clean and explicit: Each model declares exactly which field to use
Important Notes:
- Models without
seoTitleField()method won't have SEO titles (intentional) - Return a single field name, not conditional logic
- This is perfect for models where SEO is important (Product, Blog, Category) while internal models (Order, User, CartItem) simply don't define the method
Example for different models:
Populate Media Metadata
If you have existing images in your database before installing this package, you can populate their metadata:
Improvements in the latest version:
- Better model class resolution (supports both short names and full namespaces)
- Progress bar for tracking processing status
- Improved error handling and reporting
- Memory-efficient chunked processing
- Dry-run mode for testing
- Synchronous mode for immediate processing
- Automatic MIME type correction for existing records
- Enhanced MIME type detection for WebP/AVIF formats
This command will:
- Scan configured models that use the HasMultimedia trait
- Process records in batches to avoid memory issues
- Create MediaMetadata records for existing images
- Automatically fix incorrect MIME types for existing records
- Dispatch jobs to handle large datasets efficiently
- Extract file information including size, mime type, and dimensions
MIME Type Detection
The package includes robust MIME type detection that:
- Trusts file extensions for WebP and AVIF formats (PHP's built-in detection often confuses these)
- Automatically fixes mismatches when running
populate-metadatacommand - Uses multiple detection methods in priority order:
- Extension-based for WebP/AVIF (most reliable for these formats)
- PHP's
finfofunctions for other file types mime_content_type()as fallbackgetimagesize()for image validation- Extension mapping as last resort
This ensures that files like .webp are correctly identified as image/webp and not incorrectly labeled as image/avif or binary/octet-stream.
Remove Duplicate Media Metadata
Clean up duplicate media metadata records from your database:
What it does:
- Identifies duplicate records based on:
mediable_type+mediable_id+mediable_field+file_name - Shows you a preview of duplicates with counts and details
- Keeps the oldest record in each duplicate group (by
created_atandid) - Removes all other duplicates in each group
- Provides verification that cleanup was successful
Features:
- 🔍 Dry run mode to preview what will be removed
- 📊 Detailed reporting showing duplicate groups and counts
- 📋 Sample preview of duplicates before removal
- ✅ Verification to confirm cleanup was successful
- 🚀 Progress bar for large datasets
- 💾 Safe operation - always keeps the oldest record
- 🤖 Non-interactive mode with
--forceflag for automation
Example output:
This command is useful when:
- You've imported data that created duplicate metadata entries
- Migration issues caused duplicate records
- Multiple processes created metadata for the same files
- You want to clean up your database before important operations
Update Cache Headers for Existing Images
Retroactively add cache control headers to existing images in S3:
Features:
- ✅ Progress bar showing real-time progress
- 🔍 Dry run mode to preview changes
- 📁 Directory-specific updates
- 🎯 Limit option for batch processing
- 📝 Detailed output mode showing each file processed
- 📊 Summary report with success/error counts
- 🚀 Automatically detects all image directories from config
How it works:
- Uses S3's
copyObjectAPI to update metadata without re-uploading files - Applies cache control settings from your config
- Sets proper Content-Type based on file extension
- Processes original images and all resized versions
This command is essential if you have images uploaded before cache headers were implemented, ensuring all your images benefit from optimal browser and CDN caching.
💡 Tip: Verifying Cache Headers
To check if cache headers are properly set on your images, use curl:
Helper Functions
Advanced Usage
Custom Image Sizes
Define custom sizes in your config:
Disabling Automatic Resizing
To completely disable automatic image resizing, set the image_sizes config to an empty array:
This is useful when:
- You want to handle image resizing manually
- You're working with vector graphics or images that shouldn't be resized
- You want to optimize storage by keeping only original images
- You're using an external service for image processing
Exclude Certain Fields from Processing
The HasMultimedia trait automatically determines the appropriate processing based on field type:
- Image fields: Automatic resizing to configured sizes
- Video fields: Optional compression with FFmpeg
- Document fields: No processing, upload as-is
Handling Nested Arrays
For complex data structures like checkout items:
Troubleshooting
Images not resizing
- Ensure queue workers are running:
php artisan queue:work - Check that model directories are configured in
config/file-manager.php - Verify S3 permissions allow reading and writing
Duplicate resize jobs
- Use
moveTempImageWithoutResize()when the model hasHasMultimediatrait - The trait automatically handles resizing on create/update
WebP conversion failing
- Ensure GD or ImageMagick PHP extensions are installed
- Check PHP memory limit for large images
Cloudflare R2 Specific Issues
Connection Errors
- Ensure
AWS_ENDPOINTis set correctly (format:https://[account-id].r2.cloudflarestorage.com) - Always use
AWS_DEFAULT_REGION=autofor R2 - Verify your API credentials have the correct permissions
Public Access Not Working
- Enable R2.dev subdomain in bucket settings
- Or configure custom domain with Transform Rules
- Check CORS settings if accessing from browser
Upload Failures
- R2 has a 5GB single upload limit (use multipart for larger files)
- Ensure your API token has write permissions
- Check if you've reached storage limits in your Cloudflare plan
AWS S3 Specific Issues
Access Denied Errors
- Verify IAM user has correct policies attached
- Check bucket policy allows your operations
- Ensure bucket region matches your configuration
CORS Issues
- Configure CORS in bucket settings:
Slow Upload/Download
- Consider using Transfer Acceleration for S3
- Use CloudFront CDN for better performance
- Choose bucket region closer to your users
Performance Tips
- Use queues for image processing to avoid blocking requests
- Enable compression for automatic file size optimization
- Configure CDN for faster content delivery
- Set appropriate thresholds to avoid compressing small files
- Use WebP format for 25-35% smaller file sizes
- Configure cache headers for optimal browser and CDN caching:
- Set
max_ageto 31536000 (1 year) for versioned/hashed filenames - Use
publicvisibility for CDN caching - Enable
immutablefor static assets that never change
- Set
Cache Control Configuration
The package automatically adds cache headers to all uploaded media files for optimal performance:
All media files uploaded to S3 will automatically include these cache headers:
Cache-Control: public, max-age=31536000, immutable(default)- Proper
Content-Typebased on actual file format - Optimized for CDN edge caching
Cleanup Old Media
The package provides a cleanup command to delete old media files from storage based on age thresholds. This helps manage storage costs and keep your S3/R2 bucket clean.
How It Works
- Apply the
PrunableMediatrait to models that have media files - Define
prunableMediaPeriod()to specify how old files should be before deletion - The command discovers all models with the trait and deletes their old files from storage
- The
storage_deleted_attimestamp is set onmedia_metadatarecords to track cleanup state
Prerequisites
Add the storage_deleted_at column to your media_metadata table by publishing and running the migration:
Step 1: Apply the Trait
Add PrunableMedia trait to any model that has media files you want to clean up. The model must also use HasMultimedia:
Step 2: Run the Cleanup Command
What Gets Deleted
The command:
- Finds all models where
created_atis older than theprunableMediaPeriod()threshold - Collects all file paths from the model's
mediaFieldsToWatch()fields - Uses
FileManagerService::deleteImage()to delete each file — including all resized variants - Sets
storage_deleted_at = now()on the correspondingmedia_metadatarecords
The command is idempotent — re-running it skips records that already have storage_deleted_at set.
Scheduling
Add to your app/Console/Kernel.php to run weekly:
Or run manually via cron:
API Method
You can also call the cleanup logic directly from PHP:
Key Features
- Idempotent: Safely re-run — skips already-deleted files via
storage_deleted_atflag - Discovers models automatically: No configuration needed beyond applying the trait
- Handles all resized variants: Uses
FileManagerService::deleteImage()which deletes original + all sizes - Dry-run mode: Preview what would be deleted before running for real
- Configurable per model: Each model can define its own
prunableMediaPeriod()
Changelog
Please see CHANGELOG for recent changes.
Contributing
Contributions are welcome! Please see CONTRIBUTING for details.
Security
If you discover any security issues, please email [email protected] instead of using the issue tracker.
Credits
- Kiran Timsina
- RayzenTech
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
Support
For support, please open an issue on GitHub.
All versions of file-manager with dependencies
filament/filament Version ^5.0
illuminate/contracts Version ^11.0||^12.0||^13.0
illuminate/support Version ^11.0||^12.0||^13.0
intervention/image Version ^3.9
league/flysystem-aws-s3-v3 Version ^3.29
php-ffmpeg/php-ffmpeg Version ^1.2
spatie/laravel-package-tools Version ^1.16