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

Glide Laravel Package

league/glide

Glide is an on-demand PHP image manipulation library served over HTTP. Resize, crop, and apply effects with simple URL parameters, with automatic caching and far-future headers. Works with GD, Imagick, or libvips and Flysystem storage.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup in Laravel
1. **Installation**:
   ```bash
   composer require league/glide
  1. Basic Route Configuration (in routes/web.php):

    use League\Glide\ServerFactory;
    
    Route::get('/img/{path}', function ($path) {
        $server = ServerFactory::create([
            'source' => storage_path('app/public'),
            'cache' => storage_path('app/cache/glide'),
            'base_url' => '/img',
        ]);
        return $server->getImageResponse($path, $_GET);
    });
    
  2. First Use Case:

    • Upload an image to storage/app/public (e.g., profile.jpg).
    • Reference it in a Blade template:
      <img src="/img/profile.jpg?w=200&h=200&fit=crop" alt="Profile">
      
    • The URL query parameters (w, h, fit) dynamically resize the image.

Implementation Patterns

1. Dynamic Image Serving

  • Workflow:
    • Store original images in storage/app/public.
    • Use Glide to generate on-demand resized/cropped versions via URL parameters.
    • Cache processed images in storage/app/cache/glide for performance.
  • Example:
    // In a controller or service
    $server = app(ServerFactory::class)->create([
        'source' => storage_path('app/public'),
        'cache' => storage_path('app/cache/glide'),
    ]);
    return $server->getImageResponse('products/123.jpg', ['w' => 800, 'h' => 600, 'fit' => 'crop']);
    

2. Framework Integration

  • Laravel Middleware: Create middleware to handle Glide requests globally:

    // app/Http/Middleware/GlideMiddleware.php
    public function handle($request, Closure $next) {
        if ($request->is('img/*')) {
            $server = ServerFactory::create(config('glide'));
            return $server->getImageResponse($request->path(), $request->query());
        }
        return $next($request);
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\GlideMiddleware::class,
    ];
    
  • Configuration: Add to config/glide.php:

    return [
        'source' => storage_path('app/public'),
        'cache' => storage_path('app/cache/glide'),
        'base_url' => '/img',
        'driver' => 'gd', // or 'imagick', 'vips'
    ];
    

3. Reusable Helpers

  • Service Class:
    // app/Services/GlideService.php
    class GlideService {
        protected $server;
    
        public function __construct() {
            $this->server = ServerFactory::create(config('glide'));
        }
    
        public function getImageUrl($path, array $params = []) {
            return route('glide.image', ['path' => $path, 'query' => http_build_query($params)]);
        }
    
        public function getImageResponse($path, array $params = []) {
            return $this->server->getImageResponse($path, $params);
        }
    }
    
  • Usage in Blade:
    {{ $glideService->getImageUrl('products/123.jpg', ['w' => 400, 'h' => 400]) }}
    

4. Signed URLs (Security)

  • Enable HTTP signatures to prevent unauthorized access:
    $server = ServerFactory::create([
        'source' => storage_path('app/public'),
        'cache' => storage_path('app/cache/glide'),
        'signature_key' => config('app.key'),
        'signature_secret' => config('glide.signature_secret'),
    ]);
    
  • Generate signed URLs:
    $signedUrl = $server->getSignedUrl('products/123.jpg', ['w' => 300], '+1 hour');
    

Gotchas and Tips

1. Common Pitfalls

  • Cache Directory Permissions: Ensure storage/app/cache/glide is writable by the web server user (e.g., chmod -R 755 storage/app/cache/glide). Symptom: Blank images or 500 errors when processing.

  • Base URL Mismatch: If base_url is misconfigured, Glide may fail to locate source files. Fix: Verify the base_url matches your route (e.g., /img in routes but base_url set to /images).

  • Driver Limitations:

    • GD: Slower for complex operations (e.g., blur, pixelate). Avoid high values (e.g., blur=50).
    • Imagick: Faster but requires PHP Imagick extension (pecl install imagick).
    • libvips: Best performance but requires php-vips extension.
  • Query String Order: Glide processes parameters in a specific order (e.g., rect before fit). Incorrect order may yield unexpected results. Example: ?rect=100,100,200,200&w=100&h=100 (correct) vs. ?w=100&h=100&rect=100,100,200,200 (may fail).

2. Debugging Tips

  • Check Cache: Manually verify if processed images exist in storage/app/cache/glide. If not, check file permissions or driver errors.
  • Log Errors: Enable Glide’s debug mode:
    $server->setDebug(true);
    
    Errors will be logged to storage/logs/laravel.log.
  • Test with Simple Parameters: Start with basic resizing (?w=100&h=100) before adding complex effects (e.g., blur, pixel).

3. Performance Optimization

  • Predefined Sizes: Cache frequently used sizes (e.g., thumbnails) to avoid repeated processing. Example:
    $server->outputImage('products/123.jpg', ['w' => 100, 'h' => 100, 'fit' => 'crop']);
    
  • Limit Effects: Avoid CPU-intensive operations (e.g., high blur values) on large images. Use libvips for better performance.
  • CDN Integration: Serve cached images via CDN (e.g., Cloudflare) to reduce origin load.

4. Extension Points

  • Custom Manipulators: Extend Glide by adding custom manipulators (e.g., watermarks):

    use League\Glide\Api\Manipulator\ManipulatorInterface;
    
    class WatermarkManipulator implements ManipulatorInterface {
        public function manipulate($image, $params) {
            if (isset($params['watermark'])) {
                $watermark = Intervention\Image::make(public_path('watermark.png'));
                $image->insert($watermark, 'bottom-right', 10, 10);
            }
            return $image;
        }
    }
    

    Register in ServerFactory:

    $manipulators = [
        new WatermarkManipulator(),
        // ... other manipulators
    ];
    $api = new League\Glide\Api\Api($imageManager, $manipulators);
    
  • Flysystem Adapters: Use custom Flysystem adapters (e.g., S3, Dropbox) for cloud storage:

    $source = new League\Flysystem\Filesystem(
        new League\Flysystem\AwsS3\AwsS3Adapter('bucket', 'key', 'secret')
    );
    

5. Security Considerations

  • Validate Input: Sanitize $path and query parameters to prevent directory traversal:
    $path = preg_replace('/[^a-z0-9_\-\/]/i', '', $path);
    
  • Disable Cache in Development: Set cache to a temporary directory (e.g., sys_get_temp_dir()) to avoid stale cached images during development.
  • Signature Validation: Always use signed URLs for sensitive images (e.g., user uploads) to prevent hotlinking.

6. Laravel-Specific Tips

  • Artisan Command for Cache Cleanup:
    // app/Console/Commands/ClearGlideCache.php
    public function handle() {
        $cachePath = storage_path('app/cache/glide');
        if (File::exists($cachePath)) {
            File::delete
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai