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

File Manager System Laravel Package

anfallnorr/file-manager-system

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup for Laravel Integration
Updated for **1.0.54** with streamlined Symfony integration and Laravel-specific optimizations.

**1. Install via Composer**
```bash
composer require anfallnorr/file-manager-system:^1.0.54

2. Register the Service Provider (Simplified) Leverage Laravel’s built-in Symfony bridge with 1.0.54’s native Laravel adapter:

// app/Providers/FileManagerServiceProvider.php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Anfallnorr\FileManagerSystem\Laravel\FileManagerSystem;

class FileManagerServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('file-manager', function ($app) {
            return new FileManagerSystem(
                $app['filesystem']->disk('local')->getAdapter()->getPathPrefix(),
                $app['config']['filesystems.disks.local.root']
            );
        });
    }
}

Register in config/app.php:

'providers' => [
    // ...
    App\Providers\FileManagerServiceProvider::class,
],

3. First Use Case: Upload with Metadata

use Illuminate\Support\Facades\Storage;

public function uploadWithMetadata(Request $request)
{
    $fmService = app('file-manager');
    $file = $request->file('file');

    // Auto-slugify, extract metadata, and upload
    $result = $fmService->upload(
        $file,
        '/uploads',
        returnDetails: true,
        options: ['slugify' => true, 'extractMetadata' => true]
    );

    return response()->json([
        'path' => $result['relative'],
        'metadata' => $result['metadata'] ?? [],
    ]);
}

Implementation Patterns

1. Directory Management with Laravel Filesystem

Pattern: Unified Filesystem Access Use Laravel’s Storage facade alongside the package for consistency:

// Create directory via Laravel Storage
Storage::disk('local')->makeDirectory('project-assets/images');

// List via FileManager (with caching)
$directories = app('file-manager')->getDirs(
    path: 'project-assets',
    depth: '> 0',
    excludeDir: ['temp']
);

// Cache with Laravel's cache
$cachedDirs = cache()->remember('dirs:project-assets', now()->addHours(1), function () {
    return app('file-manager')->getDirs('project-assets');
});

Integration Tip: Use 1.0.54’s FileManagerSystem::setDisk() to switch between Laravel disks dynamically:

$fmService = app('file-manager');
$fmService->setDisk('s3'); // Now works with AWS S3 via Laravel
$fmService->upload($file, '/backups');

2. File Upload with Enhanced Metadata

Pattern: Structured Upload Workflow Leverage 1.0.54’s new extractMetadata option for automatic metadata extraction:

public function handleAdvancedUpload(Request $request)
{
    $fmService = app('file-manager');
    $fmService->setDefaultDirectory(storage_path('app/media'));

    $uploaded = $fmService->upload(
        $request->file('file'),
        '/products',
        returnDetails: true,
        options: [
            'slugify' => true,
            'extractMetadata' => true, // New in 1.0.54
            'overwrite' => false,
        ]
    );

    // Store in DB with metadata
    ProductImage::create([
        'path' => $uploaded['relative'],
        'mime' => $uploaded['mime'],
        'size' => $uploaded['filesize'],
        'dimensions' => $uploaded['metadata']['dimensions'] ?? null, // New
        'exif' => $uploaded['metadata']['exif'] ?? null, // New
    ]);
}

Workflow:

  1. Auto-slugify filenames (e.g., "My File.pdf""my-file.pdf").
  2. Extract metadata (dimensions, EXIF, MIME) automatically.
  3. Store relative paths in your database using Laravel’s Storage facade:
    $path = Storage::disk('local')->path($uploaded['relative']);
    

3. User-Specific File Management

Pattern: Session-Aware Contexts Use 1.0.54’s setUserContext() for user-specific directories (integrates with Laravel’s auth):

// Middleware to set user context
public function handle(Request $request, Closure $next)
{
    $fmService = app('file-manager');
    $fmService->setUserContext($request->user()->id);
    $fmService->setDefaultDirectory(
        storage_path("app/uploads/{$request->user()->id}")
    );
    return $next($request);
}

// Usage in controller
$fmService->upload($file, '/documents'); // Auto-prepends user ID

Integration Tip: Combine with Laravel’s policies for authorization:

public function authorizeUpload(Request $request)
{
    return $request->user()->can('upload_files');
}

4. Image Processing Pipeline

Pattern: Resizing with Laravel Queues Use 1.0.54’s resize() method (now optimized for Laravel):

public function resizeAndStore(Request $request)
{
    $fmService = app('file-manager');
    $uploaded = $fmService->upload($request->file('image'), '/thumbnails');

    // Resize in background (Laravel Queue)
    ResizeImageJob::dispatch($uploaded['absolute'], 300, 'webp');

    return response()->json(['path' => $uploaded['relative']]);
}

Job Example:

// app/Jobs/ResizeImageJob.php
public function handle($filePath, $width, $format)
{
    $fmService = app('file-manager');
    $fmService->resize($filePath, $width, $format);
    // Auto-save to original path (overwrite)
}

Gotchas and Tips

1. Path Handling in 1.0.54

  • Laravel Disk Compatibility: Use Storage::disk()->path() for absolute paths:
    // ✅ Correct (uses Laravel's disk)
    $path = Storage::disk('local')->path('uploads/file.jpg');
    
    // ❌ Avoid (hardcoded)
    $path = '/var/www/storage/app/uploads/file.jpg';
    
  • Relative Paths: Always use relative key from $uploaded array:
    $relativePath = $uploaded['relative']; // e.g., 'uploads/2024/file.jpg'
    $absolutePath = Storage::disk('local')->path($relativePath);
    

2. Debugging Tips for 1.0.54

  • Metadata Extraction Issues: Ensure exif and imagick PHP extensions are installed:
    sudo apt-get install php-imagick php-exif
    
  • Permission Denied: Use Laravel’s chmod() helper:
    Storage::disk('local')->chmod('uploads', 0775);
    
  • Log Upload Events: Use Laravel’s logging:
    try {
        $result = $fmService->upload($file, '/');
    } catch (\Exception $e) {
        \Log::error("Upload failed: " . $e->getMessage(), [
            'file' => $file->getClientOriginalName(),
            'user' => auth()->id(),
        ]);
    }
    

3. Extension Points in 1.0.54

  • Custom Metadata Extractors: Override the default extractor:
    $fmService->setMetadataExtractor(function ($filePath) {
        return [
            'custom_field' => 'value',
            'dimensions' => getimagesize($filePath),
        ];
    });
    
  • Event Listeners: Use Laravel’s events for post-upload actions:
    // app/Providers/FileManagerServiceProvider.php
    $fmService->upload($file, '/')->then(function ($result) {
        event(new FileUploaded($result['relative'], auth()->user()));
    });
    
  • Laravel Policy Integration: Restrict file operations per user:
    // app/Policies/FileManagerPolicy.php
    public function upload(User $user, $directory)
    {
        return $user->hasRole('editor') && $user->canAccessDirectory($directory);
    }
    

4. Performance Optimizations

  • Batch Processing: Use Laravel’s Chunk for large file listings:
    $files = app('file-manager')->getFiles('/uploads');
    \Storage::disk('local')->chunk($files, 100, function ($chunk) {
        foreach ($chunk as $file) {
            // Process in batches
        }
    });
    
  • Memory Limits: Disable metadata extraction for non-image files:
    $fmService->upload($file, '/', options:
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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