PHP code example of rayzenai / file-manager

1. Go to this page and download the library: Download rayzenai/file-manager library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rayzenai / file-manager example snippets


'default' => env('FILESYSTEM_DISK', 's3'),

'disks' => [
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        'throw' => false,
    ],
],

'temporary_file_upload' => [
    'disk' => 's3',  // Use S3 for temporary uploads
    'rules' => ['', 'gif', 'bmp', 'svg', 'wav', 'mp4',
        'mov', 'avi', 'wmv', 'mp3', 'm4a',
        'jpg', 'jpeg', 'mpga', 'webp', 'wma',
    ],
    'max_upload_time' => 5,
    'cleanup' => true,
],

'default' => env('FILESYSTEM_DISK', 'r2'),

'disks' => [
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        'throw' => false,
    ],

    'r2' => [
        'driver' => 's3',
        'key' => env('CLOUDFLARE_R2_ACCESS_KEY_ID'),
        'secret' => env('CLOUDFLARE_R2_SECRET_ACCESS_KEY'),
        'region' => 'auto',  // Always use 'auto' for R2
        'bucket' => env('CLOUDFLARE_R2_BUCKET'),
        'url' => env('CLOUDFLARE_R2_URL'),
        'visibility' => 'private',
        'endpoint' => env('CLOUDFLARE_R2_ENDPOINT'),
        'use_path_style_endpoint' => env('CLOUDFLARE_R2_USE_PATH_STYLE_ENDPOINT', false),
        'throw' => false,
    ],
],

'temporary_file_upload' => [
    'disk' => 'r2',  // Use R2 for temporary uploads
    'rules' => ['', 'gif', 'bmp', 'svg', 'wav', 'mp4',
        'mov', 'avi', 'wmv', 'mp3', 'm4a',
        'jpg', 'jpeg', 'mpga', 'webp', 'wma',
    ],
    'max_upload_time' => 5,
    'cleanup' => true,
],

    use Kirantimsina\FileManager\FileManagerPlugin;

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->plugins([
                FileManagerPlugin::make(),
            ]);
    }
    

return [
    // CDN URL for serving files
    'cdn' => env('CDN_URL', env('AWS_URL', env('APP_URL'))),

    // Maximum upload dimensions
    'max-upload-height' => '5120', // pixels
    'max-upload-width' => '5120',  // pixels

    // File upload size limits by type
    'max-upload-size-image' => '8192',     // KB - Max size for image uploads (8 MB)
    'max-upload-size-video' => '102400',   // KB - Max size for video uploads (100 MB)
    'max-upload-size-document' => '20480', // KB - Max size for document uploads (20 MB)

    // Model to directory mappings (supports full class names)
    'model' => [
        'App\Models\User' => 'users',       // Or use User::class
        'App\Models\Product' => 'products', // Or use Product::class
        'App\Models\Blog' => 'blogs',       // Or use Blog::class
        // Add your models here
    ],

    // Image sizes to generate
    // Set to empty array [] to disable automatic resizing completely
    'image_sizes' => [
        'icon' => 64,       // 64px height for small icons
        'small' => 120,     // 120px height for small thumbnails
        'thumb' => 240,     // 240px height for thumbnails
        'card' => 360,      // 360px height for card images
        'medium' => 480,    // 480px height for medium images
        'large' => 720,     // 720px height for large images
        'full' => 1080,     // 1080px height for full size
        'ultra' => 2160,    // 2160px height for ultra HD
    ],

    // Default thumbnail size for MediaColumn components
    'default_thumbnail_size' => env('FILE_MANAGER_DEFAULT_THUMBNAIL_SIZE', 'icon'),
    'default_card_size' => env('FILE_MANAGER_DEFAULT_CARD_SIZE', 'card'),

    // Cache Control Headers for Media Files
    'cache' => [
        'enabled' => env('FILE_MANAGER_CACHE_ENABLED', true),

        // Cache duration in seconds
        // Common values:
        // 3600 = 1 hour
        // 86400 = 1 day
        // 604800 = 1 week
        // 2592000 = 30 days
        // 31536000 = 1 year (default)
        'max_age' => env('FILE_MANAGER_CACHE_MAX_AGE', 31536000),

        // Cache visibility:
        // 'public' - Can be cached by browsers and CDNs
        // 'private' - Only cached by browsers, not CDNs
        'visibility' => env('FILE_MANAGER_CACHE_VISIBILITY', 'public'),

        // Immutable directive - tells browsers the file will never change
        // Recommended for versioned/hashed filenames
        'immutable' => env('FILE_MANAGER_CACHE_IMMUTABLE', true),
    ],

    // Compression settings
    'compression' => [
        'enabled' => env('FILE_MANAGER_COMPRESSION_ENABLED', true),
        'driver' => env('FILE_MANAGER_COMPRESSION_DRIVER', 'gd'), // 'gd' or 'imagick'
        'auto_compress' => env('FILE_MANAGER_AUTO_COMPRESS', true),
        'quality' => env('FILE_MANAGER_COMPRESSION_QUALITY', 85), // 1-95
        'format' => env('FILE_MANAGER_COMPRESSION_FORMAT', 'webp'), // webp, jpeg, jpg, png, avif
        'mode' => env('FILE_MANAGER_COMPRESSION_MODE', 'contain'), // contain, crop, cover
        'threshold' => env('FILE_MANAGER_COMPRESSION_THRESHOLD', 100 * 1024), // 100KB

        // Maximum allowed dimensions (hard limits - images will never exceed these)
        'max_height' => env('FILE_MANAGER_MAX_HEIGHT', 2160),
        'max_width' => env('FILE_MANAGER_MAX_WIDTH', 3840),
    ],

    // Media metadata tracking
    'media_metadata' => [
        'enabled' => env('FILE_MANAGER_METADATA_ENABLED', true),
        'track_file_size' => env('FILE_MANAGER_TRACK_FILE_SIZE', true),
        'track_dimensions' => env('FILE_MANAGER_TRACK_DIMENSIONS', true),
        'track_mime_type' => env('FILE_MANAGER_TRACK_MIME_TYPE', true),
        'model' => \Kirantimsina\FileManager\Models\MediaMetadata::class,
    ],
];

use Kirantimsina\FileManager\Traits\HasMultimedia;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasMultimedia;

    protected $fillable = [
        'name',
        'image',        // Single image field
        'gallery',      // Multiple images field
        'demo_video',   // Video field
        'manual_pdf',   // Document field
    ];

    protected $casts = [
        'gallery' => 'array', // Cast array fields
    ];

    /**
     * Define which fields contain media files and their types
     * Required by HasMultimedia trait for automatic processing
     */
    public function mediaFieldsToWatch(): array
    {
        return [
            'images' => ['image', 'gallery'],
            'videos' => ['demo_video', 'promo_video'],
            'documents' => ['manual_pdf', 'specifications'],
        ];
    }

    /**
     * Optional: Define which field should be used for SEO title generation
     * Remove this method if SEO titles are not needed for this model
     */
    public function seoTitleField(): string
    {
        return 'name'; // or 'meta_title', 'seo_title', etc.
    }
}

use Kirantimsina\FileManager\Forms\Components\MediaUpload;

// Set SEO title directly
MediaUpload::make('image')
    ->seoTitle('Premium Chocolate Cake')

// Set SEO title from another field
MediaUpload::make('image')
    ->seoTitleFromField('name')  // Uses the 'name' field value as SEO title

// Dynamic SEO title with closure
MediaUpload::make('image')
    ->seoTitle(fn (Get $get) => $get('meta_title') ?? $get('name'))

'seo' => [
    'enabled_models' => [
        'App\Models\Product',
        'App\Models\Category',
        'App\Models\Blog',
        // Models that should have SEO titles
    ],
    'excluded_models' => [
        'App\Models\User',
        'App\Models\Order',
        // Models that should NOT have SEO titles
    ],
],

use Kirantimsina\FileManager\Forms\Components\MediaUpload;

// Example 1: Convert to WebP with custom quality
MediaUpload::make('image')
    ->label('Product Image')
    ->quality(90)               // Compression quality, capped at 95
    ->toWebp()                  // Convert to WebP format

// Example 2: Compress but keep original format (JPEG stays JPEG, PNG stays PNG)
MediaUpload::make('photo')
    ->keepOriginalFormat()      // Compress but maintain original format
    ->quality(85)               // Still applies compression

// Example 3: Upload without ANY processing
MediaUpload::make('document')
    ->uploadOriginal()          // Skip all processing - no compression, no conversion

// Example 4: Full featured upload
MediaUpload::make('product_image')
    ->toAvif()                  // Convert to AVIF format (

use Kirantimsina\FileManager\Tables\Columns\MediaModalColumn;

// Basic usage with modal preview
MediaModalColumn::make('image_file_name')
    ->label('Product Image')
    ->thumbnailSize('small')
    ->modalSize('large')
    ->allowEdit() // Enable editing in modal

// With custom heading and relationship
MediaModalColumn::make('attachment_file_name')
    ->label('Attachments')
    ->relationship('attachments')
    ->heading('View Attachments')
    ->multiple() // Handle multiple images
    ->downloadable() // Allow downloads
    ->previewable() // Enable preview

// Legacy dot notation (still supported)
MediaModalColumn::make('product.image_file_name')
    ->label('Product Image')
    ->thumbnailSize('medium')

use Kirantimsina\FileManager\Tables\Columns\MediaUrlColumn;

// Basic usage - links to media page
MediaUrlColumn::make('image_file_name')
    ->label('Product Image')
    ->thumbnailSize('small')
    ->openInNewTab() // Open link in new tab

// With relationship
MediaUrlColumn::make('featured_image')
    ->label('Featured Image')
    ->relationship('media')
    ->thumbnailSize('card')

// In your model
class CartItem extends Model
{
    public function attachments(): HasMany
    {
        return $this->hasMany(AttachmentFile::class);
    }
}

// In your Filament resource
MediaColumn::make(
    field: 'attachment_file_name',  // Field on the AttachmentFile model
    relationship: 'attachments',     // Relationship method name
    showInModal: true
)

// config/file-manager.php
'default_thumbnail_size' => 'thumb', // Default for thumbnail displays
'default_card_size' => 'large',     // Default for card displays

MediaModalColumn::make('image')
    ->thumbnailSize('large') // This overrides the default

MediaUrlColumn::make('image')
    ->thumbnailSize('large') // This overrides the default

use Kirantimsina\FileManager\Tables\Columns\S3Image;

S3Image::make('image')
    ->label('Image')
    ->size('medium')     // Use specific size: 'small', 'medium', 'large'
    ->square()           // Square aspect ratio
    ->circular()         // Circular mask

use App\Models\Product;
use Kirantimsina\FileManager\Facades\FileManager;

// Upload a file
$result = FileManager::upload(
    Product::class,      // model class
    $uploadedFile,       // file
    'summer-sale',       // tag (optional)
    false,               // fit (optional, default: false)
    true,                // resize (optional, default: true)
    false,               // webp (optional, default: false)
    false                // reencode (optional, default: false)
);
$path = $result['file']; // Get the file path from result

// Upload multiple files
$result = FileManager::uploadImages(
    Product::class,      // model class
    $uploadedFiles,      // files array
    'gallery',           // tag (optional)
    false,               // fit (optional)
    true                 // resize (optional)
);
$paths = $result['files']; // Get array of file paths

// Upload base64 encoded image
$result = FileManager::uploadBase64(
    Product::class,      // model class
    $base64String,       // base64 image
    'user-upload',       // tag (optional)
    false,               // fit (optional)
    true                 // resize (optional)
);
$path = $result['file']; // Get the file path from result

// Move temp file without resizing
$path = FileManager::moveTempImageWithoutResize(
    Product::class,      // model class
    'temp/abc123.jpg'    // temp file path
);

// Move temp file with automatic resizing
$path = FileManager::moveTempImage(
    Product::class,      // model class
    'temp/abc123.jpg'    // temp file path
);

// Delete image and all its sizes
FileManager::deleteImage('products/image.jpg');

// Delete multiple images
FileManager::deleteImagesArray(['products/img1.jpg', 'products/img2.jpg']);

// Get SEO-friendly filename
$filename = FileManager::filename(
    file: $uploadedFile,
    tag: 'product-name',
    extension: 'webp'
);

// Get image URL with specific size
$url = FileManager::getMediaPath('products/image.jpg', 'medium');

// Get CDN URL
$cdnUrl = FileManager::mainMediaUrl();

// Get upload directory for a model
$directory = FileManager::getUploadDirectory(Product::class);

// Get configured image sizes
$sizes = FileManager::getImageSizes();

use Kirantimsina\FileManager\Services\ImageCompressionService;

$service = new ImageCompressionService();

// Compress and save
$result = $service->compressAndSave(
    sourcePath: '/tmp/upload.jpg',
    destinationPath: 'products/compressed.webp',
    quality: 85,
    height: 1080,
    width: null,  // Auto-calculate
    format: 'webp',
    mode: 'contain',
    disk: 's3'
);

// Compress existing S3 file
$result = $service->compressExisting(
    filePath: 'products/large-image.jpg',
    quality: 80
);

use Kirantimsina\FileManager\Forms\Components\MediaUpload;

// Quick setup with optimal settings (recommended)
MediaUpload::make('promo_video')
    ->toWebm()  // Complete WebM configuration with optimal settings

MediaUpload::make('demo_video')
    ->toMp4()   // Complete MP4 configuration with optimal settings

// Manual configuration for custom  and height
    ->videoPreset('fast')              // Encoding preset
    ->videoCrf(28)                     // Quality (0-63, lower = better)
    ->videoAsync(true)                 // Process asynchronously (recommended)

use Kirantimsina\FileManager\Services\VideoCompressionService;

$service = new VideoCompressionService();

// Compress a video
$result = $service->compress(
    video: '/path/to/video.mp4',
    outputFormat: 'webm',
    videoBitrate: 1000,
    maxWidth: 1280,
    maxHeight: 720,
    preset: 'medium',
    crf: 30
);

// Compress and save to S3
$result = $service->compressAndSave(
    video: '/path/to/video.mp4',
    outputPath: 'videos/compressed.webm',
    outputFormat: 'webm',
    videoBitrate: 800,
    maxWidth: 1920,
    maxHeight: 1080,
    preset: 'fast',
    crf: 28,
    disk: 's3'
);

// Get video metadata without compression
$metadata = $service->getVideoMetadata('/path/to/video.mp4');
// Returns: width, height, duration, bitrate, size, format, codecs, frame_rate

use Kirantimsina\FileManager\Jobs\CompressVideoJob;

// Dispatch video compression job
CompressVideoJob::dispatch(
    videoPath: 'uploads/large-video.mp4',
    outputPath: 'videos/optimized.webm',
    outputFormat: 'webm',
    videoBitrate: 1000,
    maxWidth: 1920,
    maxHeight: 1080,
    preset: 'medium',
    crf: 30,
    disk: 's3',
    modelClass: Product::class,        // Optional: link to model
    modelId: 123,                       // Optional: model ID
    modelField: 'demo_video',          // Optional: field name
    replaceOriginal: true,             // Replace original file
    deleteOriginal: false              // Delete original after compression
);

'queue' => [
    // Queue name for image processing jobs (resizing, compression)
    'images' => env('FILE_MANAGER_QUEUE_IMAGES', 'default'),

    // Queue name for video processing jobs
    'videos' => env('FILE_MANAGER_QUEUE_VIDEOS', 'default'),

    // Queue name for file deletion jobs
    'delete' => env('FILE_MANAGER_QUEUE_DELETE', 'default'),
],

    'image_sizes' => [
        'icon' => 64,
        'small' => 120,
        'xlarge' => 1440,  // Add your new size here
    ],
    

use Kirantimsina\FileManager\Traits\HasMultimedia;

class Product extends Model
{
    use HasMultimedia;

    /**
     * Define which field should be used for SEO title generation
     * This field is also monitored for changes to trigger updates
     * Default: 'name'
     */
    public function seoTitleField(): string
    {
        return 'meta_title'; // If meta_title is null/empty, SEO title will be null
    }
}

// Product model - wants SEO titles from meta_title
class Product extends Model
{
    use HasMultimedia;

    public function mediaFieldsToWatch(): array
    {
        return [
            'images' => ['image', 'gallery'],
            'videos' => ['demo_video'],
            'documents' => ['manual_pdf'],
        ];
    }

    public function seoTitleField(): string
    {
        return 'meta_title';
    }
}

// Blog model - wants SEO titles from title field
class Blog extends Model
{
    use HasMultimedia;

    public function mediaFieldsToWatch(): array
    {
        return [
            'images' => ['featured_image', 'cover_image'],
            'videos' => [],
            'documents' => [],
        ];
    }

    public function seoTitleField(): string
    {
        return 'title';
    }
}

// Order model - no SEO titles needed (internal use)
class Order extends Model
{
    use HasMultimedia;

    public function mediaFieldsToWatch(): array
    {
        return [
            'images' => ['receipt'],
            'videos' => [],
            'documents' => ['invoice_pdf'],
        ];
    }

    // No seoTitleField() method = no SEO titles for media
}

// Get image URL with specific size
$url = getImagePath('products/image.jpg', 'medium');

// Get CDN URL
$url = getCdnUrl('products/image.jpg');

// Check if file is an image
$isImage = isImageFile('document.pdf'); // false

'image_sizes' => [
    'thumbnail' => 150,
    'card' => 400,
    'hero' => 1920,
    // Add your custom sizes
],

'image_sizes' => [],

// The trait handles nested arrays intelligently
$checkout->items = [
    ['product_id' => 1, 'images' => ['image1.jpg', 'image2.jpg']],
    ['product_id' => 2, 'images' => ['image3.jpg']],
];

use Kirantimsina\FileManager\Traits\HasMultimedia;
use Kirantimsina\FileManager\Traits\PrunableMedia;

class Product extends Model
{
    use HasMultimedia, PrunableMedia;

    /**
     * Period in days after which media files should be deleted.
     * Files older than this will be removed from storage.
     */
    public static function prunableMediaPeriod(): int
    {
        return 365; // 1 year
    }

    /**
     * Define which fields contain media files
     */
    public function mediaFieldsToWatch(): array
    {
        return [
            'images' => ['thumbnail', 'gallery'],
            'documents' => ['datasheet'],
        ];
    }
}

$schedule->command('file-manager:cleanup-old-media')
    ->weekly()
    ->withoutOverlapping();

use Kirantimsina\FileManager\Facades\FileManager;

// Clean media older than 365 days for CartItem models
$result = FileManager::cleanupOldMedia(
    ageInDays: 365,
    mediableTypes: ['App\Models\CartItem'],
    dryRun: false,
    diskName: 's3'
);

// Result contains counts and messages
// $result['found']   - total records found
// $result['deleted'] - files actually deleted
// $result['errors']  - failed deletions
bash
    php artisan vendor:publish --tag="file-manager-config"
    
bash
    # Publish migration files to your app
    php artisan vendor:publish --provider="Kirantimsina\FileManager\FileManagerServiceProvider" --tag="file-manager-migrations"

    # Run the migrations
    php artisan migrate
    
bash
php artisan vendor:publish --tag="file-manager-migrations"
php artisan migrate