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 Partialcache Laravel Package

spatie/laravel-partialcache

Abandoned package that adds a Blade @cache directive to cache rendered partial HTML in Laravel (5.1+). Supports passing view data, setting cache duration, custom keys, and cache tags, with optional facade/config publishing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-partialcache
    

    For Laravel <5.5, manually register Spatie\PartialCache\PartialCacheServiceProvider in config/app.php.

  2. First Use Case: Cache a reusable Blade partial (e.g., a sidebar or header) with:

    @partialCache('sidebar', '1 hour')
        @include('partials.sidebar')
    @endPartialCache
    
    • Key: 'sidebar' (arbitrary string, used for cache tagging).
    • Duration: '1 hour' (supports any valid cache duration string, e.g., '5 minutes', '1440 minutes').
  3. Verify Cache: Check storage/framework/cache for generated files (e.g., sidebar_<hash>.html).


Implementation Patterns

Workflows

  1. Reusable Components: Cache frequently rendered, static partials (e.g., footers, navigation) to reduce Blade rendering overhead.

    @partialCache('user_dashboard_header', '24 hours')
        @include('dashboard.header', ['user' => $user])
    @endPartialCache
    
  2. Dynamic Keys: Use dynamic keys for partials with variable content (e.g., user-specific widgets):

    @partialCache("user_{$user->id}_widget", '10 minutes')
        @include('widgets.user', ['user' => $user])
    @endPartialCache
    
  3. Cache Invalidation: Clear specific partials via the facade:

    use Spatie\PartialCache\Facades\PartialCache;
    
    // Clear by key
    PartialCache::clear('sidebar');
    
    // Clear all partials
    PartialCache::clearAll();
    
  4. Integration with Events: Invalidate caches on data changes (e.g., after updating a user):

    event(new UserUpdated($user));
    // In listener:
    PartialCache::clear("user_{$user->id}_*");
    

Best Practices

  • Avoid Over-Caching: Use short durations (e.g., '5 minutes') for partials with frequent updates.
  • Combine with @cache: For full-page caching, layer @partialCache inside @cache directives.
  • Debugging: Temporarily disable caching in config/cache.php to test uncached behavior:
    'default' => env('CACHE_DRIVER', 'array'), // Use 'array' to disable file caching
    

Gotchas and Tips

Pitfalls

  1. Cache Driver Dependency:

    • The package uses Laravel’s file cache driver by default. Switch to redis or database in config/cache.php for distributed environments:
      'default' => env('CACHE_DRIVER', 'redis'),
      
    • Warning: File caching may cause issues in shared hosting (e.g., Heroku) where storage is ephemeral.
  2. Key Collisions:

    • Dynamic keys with similar prefixes (e.g., user_1_widget, user_1_widgets) may accidentally invalidate each other. Use unique separators:
      @partialCache("user_{$user->id}__widget", '10 minutes') <!-- Double underscore -->
      
  3. Blade Compilation:

    • Cached partials are compiled into static HTML files. Clear bootstrap/cache if Blade changes break rendering:
      php artisan cache:clear
      php artisan view:clear
      
  4. Abandoned Package Risks:

    • No updates since 2018. Fork the repo if you need long-term support or custom features (e.g., cache versioning).

Debugging Tips

  • Check Cache Files: Inspect storage/framework/cache for generated files. Delete them manually to force regeneration:

    rm -rf storage/framework/cache/*
    
  • Log Cache Hits/Misses: Add debug logging to app/Providers/AppServiceProvider.php:

    use Spatie\PartialCache\PartialCache;
    
    public function boot()
    {
        PartialCache::setLogger(function ($key, $hit) {
            \Log::debug("PartialCache [$key]: " . ($hit ? 'HIT' : 'MISS'));
        });
    }
    
  • Test with @if Fallbacks: Safeguard partials with fallback logic:

    @partialCache('sidebar', '1 hour')
        @includeIf(file_exists(resource_path('views/partials/sidebar.blade.php')), 'partials.sidebar')
    @endPartialCache
    

Extension Points

  1. Custom Cache Path: Override the cache directory in config/partialcache.php (if present) or publish the config:

    php artisan vendor:publish --provider="Spatie\PartialCache\PartialCacheServiceProvider"
    
  2. Cache Versioning: Add a version suffix to keys to invalidate all cached partials during deployments:

@partialCache("v{$app->version}_sidebar", '1 hour')


3. **Conditional Caching**:
 Use Blade `@if` to conditionally cache partials:
 ```blade
@if(auth()->check())
    @partialCache("user_{$user->id}_dashboard", '1 hour')
        @include('dashboard.content')
    @endPartialCache
@endif
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