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

Statamic Responsive Images Laravel Package

spatie/statamic-responsive-images

Statamic addon by Spatie that adds a responsive image fieldtype with art direction and breakpoint support. Automatically generates responsive variants on asset upload and renders them in Antlers via the responsive tag, with configurable breakpoints and options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/statamic-responsive-images
    

    No additional configuration is required for basic usage.

  2. Fieldtype Usage: Add the responsive fieldtype to your Statamic blueprint:

    fields:
      hero_image:
        type: responsive
        display: Hero Image
        container: assets
        allow_uploads: true
    
  3. First Use Case: Render the image in your Twig template:

    {{ responsive:hero_image }}
    

    This generates responsive <img> tags with srcset and sizes attributes, optimized for different viewport sizes.


Implementation Patterns

Core Workflow

  1. Art Direction: Define breakpoints in config/responsive-images.php (default: Tailwind breakpoints):

    'breakpoints' => ['sm', 'md', 'lg', 'xl', '2xl'],
    

    Use breakpoint-specific parameters in Twig:

    {{ responsive:hero_image ratio="16/9" lg:ratio="4/3" }}
    
  2. Dynamic Asset Swapping: Override assets per breakpoint:

    {{ responsive:hero_image :lg:src="desktop_hero" :2xl:src="large_desktop_hero" }}
    
  3. Quality Control: Set global quality in config:

    'quality' => [
        'webp' => 80,
        'avif' => 75,
    ],
    

    Override per breakpoint or format:

    {{ responsive:hero_image quality:webp="50" md:quality:webp="75" }}
    

Integration Tips

  • Glide Integration: Pass Glide parameters with glide: prefix:

    {{ responsive:hero_image glide:width="1200" glide:blur="10" }}
    

    Note: glide:width acts as a max-width to prevent oversized images.

  • Placeholder Handling: Disable placeholders for performance-critical images:

    {{ responsive:hero_image placeholder="false" }}
    
  • Format Control: Toggle WebP/AVIF globally or per tag:

    {{ responsive:hero_image webp="true" avif="false" }}
    

    Or in config/responsive-images.php:

    'webp' => true,
    'avif' => env('ENABLE_AVIF', false),
    
  • HTML Attributes: Add custom attributes dynamically:

    {{ responsive:hero_image alt="{title}" class="lazyload" loading="lazy" }}
    
  • GraphQL: Fetch responsive data in GraphQL:

    {
      entries {
        data {
          hero_image {
            responsive(ratio: "16/9") {
              sources {
                srcSet
                mediaString
              }
            }
          }
        }
      }
    }
    

Gotchas and Tips

Pitfalls

  1. Asset Caching:

    • Issue: Disabling statamic.assets.image_manipulation.cache (recommended) means the first load generates images on-demand, which can be slow.
    • Fix: Use a CDN or pre-generate critical images via the responsive:regenerate command:
      php please responsive:regenerate
      
      Note: Only works if statamic.assets.image_manipulation.cache is true.
  2. Breakpoint Mismatch:

    • Issue: Incorrect ratios or assets when breakpoints in config don’t match Twig usage.
    • Fix: Validate breakpoints in config/responsive-images.php and Twig templates. Example:
      {{ responsive:hero_image lg:ratio="16/9" }}  {# Ensure 'lg' exists in config #}
      
  3. Queue Delays:

    • Issue: Image generation jobs may delay rendering if using queues (e.g., Horizon).
    • Fix: Monitor queue backlogs or disable queues for development:
      'queue' => env('QUEUE_CONNECTION', 'sync'),  {# Force sync for testing #}
      
  4. Placeholder Artifacts:

    • Issue: Placeholders may not match final image dimensions if ratios change dynamically.
    • Fix: Use placeholder="false" or ensure consistent ratios across breakpoints.
  5. Excluded Containers:

    • Issue: Images in excluded containers (e.g., PDFs) won’t generate variants.
    • Fix: Add container handles to excluded_containers in config:
      'excluded_containers' => ['pdfs', 'videos'],
      

Debugging Tips

  • View Generation: Publish views for customization:

    php artisan vendor:publish --provider="Spatie\ResponsiveImages\ServiceProvider"
    

    Modify resources/views/vendor/responsive-images/default.blade.php.

  • Log Breakpoints: Debug breakpoint logic by logging the active breakpoint in Twig:

    {{ dump(responsive_breakpoint) }}
    
  • Glide Parameters: Validate Glide parameters with:

    {{ responsive:hero_image glide:width="invalid" }}  {# Will throw an error #}
    

Performance Quirks

  1. Dimension Calculator:

    • Threshold: Adjust dimension_calculator_threshold in config to control when images are regenerated:
      'dimension_calculator_threshold' => 0.1,  {# Default: 0.1 #}
      
    • Use Case: Lower values (e.g., 0.01) regenerate more frequently but reduce storage.
  2. AVIF Fallback:

    • Browser Support: AVIF may not work in older browsers. Use a polyfill or fallback:
      {{ responsive:hero_image avif="true" fallback="webp" }}
      
  3. Live Preview:

    • Hot Reload: Enable for Statamic 4+ to see changes instantly:
      'live_preview' => true,
      

Extension Points

  1. Custom Breakpoints: Extend breakpoints dynamically via a service provider:

    Spatie\ResponsiveImages\ResponsiveImages::extendBreakpoints(function () {
        return ['custom' => 1024];
    });
    
  2. Job Queues: Override the default queue for specific containers:

    'queues' => [
        'default' => 'default',
        'hero_images' => 'high',
    ],
    

    Then tag images:

    {{ responsive:hero_image queue="hero_images" }}
    
  3. Asset Events: Listen for asset uploads to trigger custom logic:

    use Spatie\ResponsiveImages\Events\ResponsiveImageGenerated;
    
    ResponsiveImageGenerated::listen(function ($event) {
        // Log or process generated images
    });
    
  4. GraphQL Extensions: Add custom fields to GraphQL responses by extending the ResponsiveImage type in a service provider.

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