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

On-demand image manipulation server for PHP. Resize, crop, and apply effects via a simple HTTP API. Automatically caches transformed images with far-future headers, supports GD/Imagick/libvips, Flysystem storage, multiple response types, and signed URLs for security.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require league/glide
  1. Basic Server Initialization (in a Laravel route or service provider):
    use League\Glide\ServerFactory;
    
    $server = ServerFactory::create([
        'source' => storage_path('app/public/images'), // Original images
        'cache' => storage_path('app/public/cache'),  // Processed images cache
    ]);
    
  2. First Use Case:
    • Route a URL like /images/{filename} to a controller method:
      public function serveImage(Request $request, string $filename) {
          return $server->outputImage($filename, $request->query());
      }
      
    • Use in Blade:
      <img src="/images/profile.jpg?w=200&h=200&fit=crop">
      

Key First Steps

  • Configure source (original images) and cache (processed images) paths.
  • Use ServerFactory::create() for quick setup.
  • Test with a single image URL to verify transformations (e.g., ?w=500&h=500).

Implementation Patterns

Core Workflows

  1. Dynamic Image Serving:

    • Use outputImage() with $request->query() to dynamically handle all URL parameters (e.g., ?w=300&h=300&fit=crop).
    • Example:
      $server->outputImage('product.jpg', $request->query());
      
  2. Static Transformations:

    • Predefine transformations in Blade or views:
      <img src="/images/hero.jpg?w=1200&fm=webp&q=80">
      
  3. Framework Integration:

    • Laravel Middleware:
      public function handle(Request $request, Closure $next) {
          $path = $request->path();
          if (str_starts_with($path, 'images/')) {
              $filename = substr($path, 7);
              return $server->outputImage($filename, $request->query());
          }
          return $next($request);
      }
      
    • Route Grouping:
      Route::prefix('images')->group(function () {
          Route::get('{filename}', [ImageController::class, 'serve']);
      });
      
  4. Caching Strategies:

    • Leverage Glide’s built-in cache (configured via cache path).
    • Set far-future Cache-Control headers automatically.
    • Clear cache manually when needed:
      $server->getCache()->delete('path/to/cached/image.jpg');
      

Advanced Patterns

  1. Custom Manipulators:

    • Extend League\Glide\Api\Manipulator\AbstractManipulator to add new effects (e.g., watermarks).
    • Register in the server:
      $manipulators = [
          // Default manipulators...
          new App\Glide\Manipulators\Watermark(),
      ];
      $api = new League\Glide\Api\Api($imageManager, $manipulators);
      $server = new League\Glide\Server($source, $cache, $api);
      
  2. Signed URLs:

    • Secure image URLs with HTTP signatures:
      $server->setSignatureKey('your-secret-key');
      $signedUrl = $server->getSignedUrl('image.jpg', ['w' => 500], '+1 hour');
      
  3. Storage Integration:

    • Use Flysystem adapters (e.g., S3, Dropbox) for remote storage:
      $source = new League\Flysystem\Filesystem(
          new League\Flysystem\AwsS3Adapter(...)
      );
      
  4. Batch Processing:

    • Pre-generate thumbnails for common sizes during upload:
      $server->outputImage('original.jpg', ['w' => 100, 'h' => 100]);
      $server->outputImage('original.jpg', ['w' => 300, 'h' => 300]);
      

Gotchas and Tips

Common Pitfalls

  1. Path Mismatches:

    • Ensure source path matches the actual location of original images.
    • Use base_url to avoid prefix conflicts (e.g., /images/ in URLs but not in filesystem paths).
  2. Cache Invalidation:

    • Deleting original images won’t remove cached versions. Clear cache manually or use a post-delete event.
  3. Driver Limitations:

    • GD: Slower for complex operations (e.g., blur, pixelate). Prefer imagick or libvips for performance.
    • Imagick: Requires PHP Imagick extension. Check phpinfo() for availability.
  4. URL Encoding:

    • Ensure filenames in URLs are URL-encoded (e.g., my image.jpgmy%20image.jpg).
  5. Memory Limits:

    • Large images may hit PHP’s memory_limit. Adjust or use imagick/libvips for better handling.

Debugging Tips

  1. Check Cache Path:

    • Verify the cache directory is writable and has sufficient space.
  2. Log Manipulations:

    • Enable debug mode to log transformations:
      $server->getApi()->setDebug(true);
      
  3. Validate Parameters:

    • Use try-catch for invalid parameters (e.g., negative width):
      try {
          $server->outputImage('image.jpg', $request->query());
      } catch (\League\Glide\Exceptions\InvalidManipulationException $e) {
          abort(400, $e->getMessage());
      }
      
  4. Test Locally:

    • Use php artisan serve to test image URLs before deploying.

Performance Optimization

  1. Predefined Sizes:

    • Cache common sizes (e.g., thumbnails) to avoid repeated processing.
  2. Format Selection:

    • Use webp for smaller file sizes (supported in modern browsers):
      <img src="/image.jpg?fm=webp&q=80">
      
  3. Driver Prioritization:

    • Configure the fastest available driver in ServerFactory:
      ServerFactory::create([
          'source' => storage_path('images'),
          'cache' => storage_path('cache'),
          'driver' => 'imagick', // or 'libvips'
      ]);
      
  4. Lazy Loading:

    • Combine with Laravel’s lazy directive for offscreen images:
      <img src="/image.jpg?w=500" loading="lazy">
      

Extension Points

  1. Custom Responses:

    • Override response headers or formats by extending League\Glide\Response\AbstractResponse.
  2. Middleware Integration:

    • Add authentication or rate limiting via Laravel middleware before outputImage().
  3. Event Listeners:

    • Listen for image processing events (e.g., glide.image.processed) to log or analyze usage.
  4. Testing:

    • Mock the Server in unit tests:
      $mockServer = Mockery::mock(League\Glide\Server::class);
      $mockServer->shouldReceive('outputImage')->andReturn('mocked-response');
      

```markdown
### Laravel-Specific Tips
1. **Service Provider Setup**:
   - Bind Glide to the container for dependency injection:
     ```php
     public function register() {
         $this->app->singleton(League\Glide\Server::class, function ($app) {
             return ServerFactory::create([
                 'source' => $app->storagePath('app/public/images'),
                 'cache' => $app->storagePath('app/public/cache'),
                 'driver' => config('glide.driver', 'gd'),
             ]);
         });
     }
     ```

2. **Configuration File**:
   - Add to `config/glide.php`:
     ```php
     return [
         'driver' => env('GLIDE_DRIVER', 'gd'),
         'source' => storage_path('app/public/images'),
         'cache' => storage_path('app/public/cache'),
         'base_url' => '/images',
     ];
     ```

3. **Artisan Command**:
   - Create a command to clear the cache:
     ```php
     php artisan glide:clear-cache
     ```

4. **View Composers**:
   - Inject the Glide server into views:
     ```php
     View::composer('*', function ($view) {
         $view->with('glide', app(League\Glide\Server::class));
     });
     ```
     Usage in Blade:
     ```html
     <img src="{{ $glide->getSignedUrl('image.jpg', ['w' => 300], '+1 hour') }}">
     ```

5. **Queue Processing**:
   - Offload heavy processing to queues:
     ```php
     dispatch(new ProcessImageJob('image.jpg', ['w' => 1000, 'h' =>
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport