PHPackages                             iperamuna/laravel-html-fragment-cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. iperamuna/laravel-html-fragment-cache

ActiveLibrary[Templating &amp; Views](/categories/templating)

iperamuna/laravel-html-fragment-cache
=====================================

A lightweight, generic HTML fragment caching package for Laravel. Cache any rendered HTML by identifier with support for all Laravel cache drivers, Blade directives, and simple invalidation.

v1.0.2(8mo ago)111MITPHPPHP &gt;=8.2CI passing

Since Oct 15Pushed 8mo agoCompare

[ Source](https://github.com/iperamuna/laravel-html-fragment-cache)[ Packagist](https://packagist.org/packages/iperamuna/laravel-html-fragment-cache)[ Docs](https://github.com/iperamuna/laravel-html-fragment-cache)[ GitHub Sponsors](https://github.com/iperamuna)[ RSS](/packages/iperamuna-laravel-html-fragment-cache/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (5)Versions (4)Used By (0)

Laravel HTML Fragment Cache
===========================

[](#laravel-html-fragment-cache)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6441e34c415d88b909d6ccaa7150fb0d873cec37e8179399ab64e3f90143e045/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69706572616d756e612f6c61726176656c2d68746d6c2d667261676d656e742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iperamuna/laravel-html-fragment-cache)[![Total Downloads](https://camo.githubusercontent.com/a4a1ccf8c3d4e55cd29ec085fe9ff08ba142c1d522a05c229a9b82e48fdd696e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69706572616d756e612f6c61726176656c2d68746d6c2d667261676d656e742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iperamuna/laravel-html-fragment-cache)[![License](https://camo.githubusercontent.com/54e5057de5875a67336a1ef2e7ae9b97957b8d4ec8380b6c18e81141d64ad11f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f69706572616d756e612f6c61726176656c2d68746d6c2d667261676d656e742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iperamuna/laravel-html-fragment-cache)

A lightweight, **generic HTML fragment caching** package for Laravel. Cache any rendered HTML **by identifier** (customer/org/user/etc.) with support for all Laravel cache drivers, Blade directives, and simple invalidation.

Features
--------

[](#features)

- 🚀 **Laravel 10/11/12** compatible
- 💾 **Universal cache support** - Works with Redis, Memcached, Database, File, Array, DynamoDB, and Octane
- 🎯 **Identifier-based caching** - Cache by customer, organization, user, or any identifier
- 🏷️ **Blade directive** - Simple `@fragmentCache` directive for quick caching
- ⚡ **Performance optimized** - Skip database queries and Blade rendering on cache hits
- 🔧 **Configurable cache store** - Use any cache store from your Laravel configuration
- 🎨 **Clean API** - Simple facade and trait-based usage
- 🛠️ **Artisan commands** - Interactive commands for cache management

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require iperamuna/laravel-html-fragment-cache
```

The package will automatically register its service provider and facade.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --provider="Iperamuna\HtmlFragmentCache\HtmlFragmentCacheServiceProvider" --tag=config
```

This will publish `config/fragment-cache.php` where you can customize the default settings.

Configuration
-------------

[](#configuration)

The package uses Laravel's cache system and supports all cache drivers. You can configure which cache store to use and enable/disable caching globally:

```
# In your .env file
FRAGMENT_CACHE_ENABLED=true
FRAGMENT_CACHE_STORE=redis
# or
FRAGMENT_CACHE_STORE=memcached
# or
FRAGMENT_CACHE_STORE=database
# etc.
```

### Available Configuration Options

[](#available-configuration-options)

```
// config/fragment-cache.php
return [
    // Enable or disable fragment caching globally
    'enabled' => env('FRAGMENT_CACHE_ENABLED', true),

    // Cache store to use for fragment caching (must be one from config/cache.php stores)
    'cache_store' => env('FRAGMENT_CACHE_STORE', 'default'),

    // Default TTL for cached fragments
    'default_ttl' => env('FRAGMENT_CACHE_TTL', '6 hours'),

    // Default key parts
    'variant' => env('FRAGMENT_CACHE_VARIANT', 'html_fragment'),
    'version' => env('FRAGMENT_CACHE_VERSION', 'v1'),

    // Identifier resolution
    'identifier' => [
        'prefix' => env('FRAGMENT_CACHE_ID_PREFIX', ''),
        'sources' => [
            ['type' => 'property', 'path' => 'customer.id', 'label' => 'customer'],
            ['type' => 'property', 'path' => 'organization.id', 'label' => 'org'],
            ['type' => 'route', 'name' => 'customer', 'label' => 'customer'],
            ['type' => 'route', 'name' => 'organization', 'label' => 'org'],
        ],
        'resolver' => Iperamuna\HtmlFragmentCache\Resolvers\DefaultIdentifierResolver::class,
    ],
];
```

### Enabling/Disabling Caching

[](#enablingdisabling-caching)

You can globally enable or disable fragment caching using the `enabled` configuration option:

```
# Disable fragment caching (useful for development or debugging)
FRAGMENT_CACHE_ENABLED=false

# Enable fragment caching (default)
FRAGMENT_CACHE_ENABLED=true
```

When caching is disabled:

- All `rememberHtml()` calls will execute the builder function directly without caching
- `forget()` calls will do nothing
- Blade directives will render content directly without caching
- This is useful for development, debugging, or when you want to temporarily disable caching

Usage
-----

[](#usage)

### Basic Usage with Facade

[](#basic-usage-with-facade)

```
use FragmentCache;

public function show(Customer $customer)
{
    $html = FragmentCache::rememberHtml(
        identifier: "customer:{$customer->id}",
        builder: function () use ($customer) {
            $products = $customer->products()
                ->select('id','name','image_url','category')
                ->orderBy('name')
                ->get();

            return view('components.dashboard.products-widget', compact('products'))->render();
        },
        ttl: '6 hours',
        variant: 'products_widget_html',
        version: 'v1'
    );

    return view('dashboard.index', ['productsWidgetHtml' => $html]);
}
```

### Blade Directive

[](#blade-directive)

The package provides a convenient Blade directive for quick caching:

```
@fragmentCache('customer:'.$customer->id)
    {{-- expensive HTML here --}}

        @foreach($customer->products as $product)
            {{ $product->name }}
        @endforeach

@endFragmentCache
```

You can also pass an **array** as identifier to include additional context:

```
@fragmentCache([$customer->id, app()->getLocale(), 'v2'])
    {{-- HTML with locale and version context --}}
@endFragmentCache
```

### Using the Trait

[](#using-the-trait)

For more complex scenarios, use the `UsesHtmlFragmentCache` trait:

```
use Iperamuna\HtmlFragmentCache\Concerns\UsesHtmlFragmentCache;

class ProductController extends Controller
{
    use UsesHtmlFragmentCache;

    public function show(Customer $customer)
    {
        $html = $this->cacheFragmentHtml(
            identifier: "customer:{$customer->id}",
            builder: function () use ($customer) {
                return view('components.products-widget', [
                    'products' => $customer->products()->orderBy('name')->get()
                ])->render();
            },
            variant: 'products_widget',
            version: 'v1'
        );

        return view('dashboard.index', ['productsWidgetHtml' => $html]);
    }
}
```

Livewire Integration
--------------------

[](#livewire-integration)

Perfect for caching expensive Livewire component rendering:

### Using the Trait (Recommended)

[](#using-the-trait-recommended)

```
