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

Laravel Glide Laravel Package

spatie/laravel-glide

Laravel wrapper around League Glide for easy image manipulation and caching. Create, resize, crop, apply filters, and save images via a fluent API (e.g., width, greyscale). Supports GD or Imagick, with configurable settings and a convenient facade.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-glide
    

    Publish the config file (optional):

    php artisan vendor:publish --provider="Spatie\GlideLaravel\GlideServiceProvider"
    
  2. First Use Case: Generate a resized image URL in a Blade template:

    <img src="{{ Glide::image('path/to/image.jpg')->width(200)->url() }}">
    

    Or programmatically:

    $url = Glide::image('path/to/image.jpg')->width(200)->url();
    
  3. Key Configurations:

    • Check config/glide.php for storage paths, cache settings, and response headers.
    • Ensure the glide disk (default: public) exists in config/filesystems.php.

Implementation Patterns

Core Workflows

  1. URL Generation (Most Common):

    // Basic resizing
    Glide::image('image.jpg')->width(300)->height(200)->url();
    
    // With transformations
    Glide::image('image.jpg')
        ->fit(300, 200)
        ->blur(10)
        ->text('Hello', 50, 50, 'white', 'Arial')
        ->url();
    
  2. Direct File Output:

    GlideImage::create(storage_path('app/image.jpg'))
        ->modify(['w' => 500, 'filt' => 'grayscale'])
        ->save(storage_path('app/resized.jpg'));
    
  3. Cache Control:

    • Use cache() to force caching (e.g., for thumbnails):
      Glide::image('image.jpg')->width(100)->cache();
      
    • Disable caching for dynamic images:
      Glide::image('image.jpg')->width(100)->noCache();
      
  4. Middleware Integration:

    • Add Spatie\GlideLaravel\Http\Middleware\HandleGlideRequests to your $middleware array in app/Http/Kernel.php.
    • Configure routes in routes/web.php:
      Route::glide('images/{filename}', function () {
          return Glide::image('images/' . $filename);
      });
      
  5. Dynamic Image Generation:

    • Use Glide::generate() for server-side processing:
      Glide::generate('image.jpg', function ($image) {
          $image->width(400)->height(400)->circle();
      });
      

Advanced Patterns

  1. Custom Disk Handling: Override the default disk for specific images:

    Glide::image('image.jpg')->disk('s3')->width(200)->url();
    
  2. Response Headers: Customize headers per request:

    Glide::image('image.jpg')->width(200)->responseHeaders(['Cache-Control' => 'public, max-age=31536000']);
    
  3. Queue Processing: Offload heavy processing to queues:

    Glide::image('large-image.jpg')
        ->width(1000)
        ->queue()
        ->url(); // Returns a URL to the queued job's result
    
  4. Blade Directives: Create a custom Blade directive for reusable transformations:

    Blade::directive('glide', function ($expression) {
        return "<?php echo Glide::image({$expression})->width(200)->url(); ?>";
    });
    

    Usage:

    <img src="{{ glide('image.jpg') }}">
    

Gotchas and Tips

Common Pitfalls

  1. Path Resolution:

    • Ensure paths in glide.php (source_path, cache_path) are absolute and writable.
    • Use public_path(), storage_path(), or base_path() for dynamic paths:
      Glide::image(public_path('images/image.jpg'))->width(200)->url();
      
  2. Cache Invalidation:

    • Clearing the cache manually:
      php artisan glide:clear
      
    • Cache may persist even after file changes; use noCache() or unique query strings (e.g., ?t=123) for testing.
  3. Memory Limits:

    • Large images may hit PHP memory limits. Use ->queue() or optimize with ->fit() instead of ->width()/->height().
    • Increase memory_limit in php.ini if needed (e.g., 2048M).
  4. File Permissions:

    • Ensure the glide disk’s storage directory is writable:
      chmod -R 755 storage/app/public/glide-cache
      
  5. Route Conflicts:

    • If using route-based Glide, ensure no other routes conflict with /glide/*.
    • Test with php artisan route:list after adding middleware.
  6. Image Formats:

    • Glide defaults to webp for modern browsers. Force formats with:
      Glide::image('image.jpg')->format('png')->url();
      

Debugging Tips

  1. Log Transformations: Enable debug mode in glide.php:

    'debug' => env('GLIDE_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  2. Check Generated URLs: Inspect the final URL for errors (e.g., missing query params):

    dd(Glide::image('image.jpg')->width(200)->toResponse()->getOriginalContent());
    
  3. Validate Input:

    • Use Glide::validateImage() to check if a path is processable:
      if (!Glide::validateImage('image.jpg')) {
          abort(404);
      }
      
  4. Test Locally:

    • Use php artisan glide:test to verify setup.

Performance Optimization

  1. Cache Aggressively:

    • Set long Cache-Control headers for static thumbnails:
      Glide::image('thumbnail.jpg')->width(100)->cache()->responseHeaders(['Cache-Control' => 'public, max-age=31536000']);
      
  2. Lazy Load:

    • Use loading="lazy" in Blade:
      <img src="{{ Glide::image('image.jpg')->width(200)->url() }}" loading="lazy">
      
  3. Pre-Generate Images:

    • For critical images, pre-generate and store them in the database (e.g., as long_text or S3 objects).

Extension Points

  1. Custom Filters: Extend Glide’s filters by creating a custom service provider:

    use League\Glide\Responses\LaravelResponseFactory;
    use League\Glide\Server;
    
    class CustomGlideServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton(Server::class, function ($app) {
                $server = new Server(storage_path('app'), new LaravelResponseFactory($app['request']));
                $server->addFilter(new CustomFilter());
                return $server;
            });
        }
    }
    
  2. Override Responses: Customize the response factory for non-Laravel apps:

    Glide::setResponseFactory(new CustomResponseFactory());
    
  3. Hooks: Use Laravel’s service container to inject middleware or decorators:

    $this->app->extend('glide', function ($glide) {
        $glide->addMiddleware(new CustomGlideMiddleware());
        return $glide;
    });
    
  4. Queue Drivers: Configure the queue driver for ->queue() in glide.php:

    'queue' => [
        'driver' => 'database',
        'connection' => 'mysql',
        'table' => 'glide_jobs',
    ],
    
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