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 with an HTTP API. Resize, crop, and apply effects, then cache results with far-future headers. Works with GD, Imagick, or libvips, integrates with Flysystem, and can sign URLs for security.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/glide
    

    Add to composer.json if using Laravel’s require or require-dev as needed.

  2. Basic Server Initialization:

    use League\Glide\ServerFactory;
    
    $server = ServerFactory::create([
        'source' => storage_path('app/public/images'), // Original images
        'cache' => storage_path('app/public/cache'),   // Processed images
    ]);
    
  3. First Use Case: In a Laravel route or controller:

    Route::get('/images/{path}', function ($path) use ($server) {
        return $server->outputImage($path, $_GET);
    });
    

    Access via URL: /images/photo.jpg?w=300&h=300&fit=crop


Implementation Patterns

Core Workflows

  1. Dynamic Image Serving:

    • Use $server->outputImage($path, $query) to handle requests dynamically.
    • Example: Resize, crop, and apply effects on-the-fly without pre-processing.
  2. Framework Integration:

    • Laravel: Use middleware to route /images/* to Glide:
      Route::get('/images/{path}', function ($path) {
          $server = app(ServerFactory::class)->create();
          return $server->outputImage($path, request()->query());
      });
      
    • Symfony: Inject Server into controllers or use a GlideListener for PSR-7 responses.
  3. Caching Strategy:

    • Leverage Glide’s built-in cache (Flysystem) to store processed images.
    • Configure cache TTL via Cache::setCacheTTL() (default: 1 year).
  4. URL Generation:

    • Generate signed URLs for security:
      $url = $server->getImageUrl('photo.jpg', ['w' => 300], 3600); // Expires in 1 hour
      

Advanced Patterns

  1. Custom Manipulators: Extend League\Glide\Api\Manipulator\AbstractManipulator to add new effects (e.g., watermarks):

    class WatermarkManipulator extends AbstractManipulator {
        public function __invoke($image, $params) {
            $image->insert('watermark.png', 'bottom-right');
        }
    }
    

    Register in ServerFactory:

    $server = ServerFactory::create([
        'source' => '...',
        'cache' => '...',
        'manipulators' => [new WatermarkManipulator()],
    ]);
    
  2. Multi-Environment Config: Use Laravel’s config system to switch sources/caches per environment:

    $server = ServerFactory::create([
        'source' => config('glide.source'),
        'cache' => config('glide.cache'),
    ]);
    

    Define in config/glide.php:

    'source' => env('GLIDE_SOURCE', storage_path('app/public/images')),
    'cache' => env('GLIDE_CACHE', storage_path('app/public/cache')),
    
  3. Storage Backends: Use Flysystem adapters for cloud storage (S3, GCS):

    $source = new Filesystem(new S3Adapter([
        'bucket' => 'my-bucket',
        'key' => 'images',
    ]));
    $server = new Server($source, $cache, $api);
    

Gotchas and Tips

Pitfalls

  1. Path Resolution:

    • Issue: URLs like /images/user/photo.jpg may fail if base_url isn’t set.
    • Fix: Configure base_url in ServerFactory:
      ServerFactory::create(['base_url' => '/images']);
      
  2. Image Driver Performance:

    • Issue: GD may struggle with heavy effects (e.g., blur=50). Use imagick or libvips for better performance.
    • Fix: Set driver in ServerFactory:
      ServerFactory::create([
          'image_manager' => new ImageManager(['driver' => 'imagick']),
      ]);
      
  3. Cache Invalidation:

    • Issue: Deleting original images won’t clear cached versions.
    • Fix: Implement a cache cleanup script or use Flysystem’s delete() for both source and cache.
  4. Query String Parsing:

    • Issue: Special characters (e.g., &, =) in filenames may break parsing.
    • Fix: URL-encode paths or use rawurlencode():
      $path = rawurlencode($path);
      

Debugging Tips

  1. Log Manipulation Steps: Enable debug mode to log API calls:

    $server->getApi()->setDebug(true);
    
  2. Check Cache Directory: Verify write permissions for the cache folder (e.g., storage/app/public/cache).

  3. Validate Image Paths: Use Filesystem::has() to check if source images exist before processing.

Extension Points

  1. Custom Responses: Extend League\Glide\Response\AbstractResponse to add headers or modify output:

    class CustomResponse extends AbstractResponse {
        public function getHeaders() {
            return ['X-Custom-Header' => 'Glide'];
        }
    }
    

    Register in ServerFactory:

    ServerFactory::create(['response' => new CustomResponse()]);
    
  2. Signature Validation: Secure URLs with HTTP signatures:

    $url = $server->getImageUrl('photo.jpg', ['w' => 300], 3600, 'secret-key');
    

    Validate in middleware:

    if (!$server->validateSignature(request()->query())) {
        abort(403);
    }
    
  3. Event Listeners: Hook into Glide’s lifecycle (e.g., post-processing) via League\Glide\Events\ImageProcessed:

    event(new ImageProcessed($image, $path, $query));
    

Laravel-Specific Tips

  1. Service Provider: Bind ServerFactory in AppServiceProvider:

    $this->app->singleton(ServerFactory::class, function () {
        return new ServerFactory([
            'source' => storage_path('app/public/images'),
            'cache' => storage_path('app/public/cache'),
        ]);
    });
    
  2. Blade Directives: Create a helper for Blade templates:

    Blade::directive('glide', function ($path) {
        return "<?php echo app('glide')->getImageUrl($path, request()->query()); ?>";
    });
    

    Usage:

    <img src="{{ glide('photo.jpg?w=300') }}" alt="Photo">
    
  3. Artisan Commands: Add a command to clear cache:

    Artisan::command('glide:clear', function () {
        $server = app(ServerFactory::class)->create();
        $cache = $server->getCache();
        $cache->delete($cache->listContents()['contents']);
    });
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony