Laravel

How to create custom Blade @cache directive that auto-invalidates on model changes?

December 3, 2025

download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Register paired directives in AppServiceProvider::boot() using Blade::directive() to wrap Cache::tags()->remember(). Pair @cache('key', 3600) with @endcache using output buffering. Model observers listen for updated/saved events to flush cache tags by table name, ensuring automatic invalidation when data changes. View cache clears with php artisan view:clear.

Example:-

Code

// AppServiceProvider.php
public function boot()
{
    Blade::directive('cache', fn($expression) => "remember({$expression}, now()->addHour(), function() { ?>");
    Blade::directive('endcache', fn() => 'get(ob_get_clean()) ?? ob_get_clean(); ?>');
}

// app/Models/Post.php
protected static function booted()
{
    static::updated(fn($model) => Cache::tags(['views', $model->getTable()])->flush());
}
      
Hire Now!

Need Help with Laravel Development ?

Work with our skilled laravel developers to accelerate your project and boost its performance.
**Hire now**Hire Now**Hire Now**Hire now**Hire now

How to create custom Blade @cache directive that auto-invalidates on model changes?

Register paired directives in AppServiceProvider::boot() using Blade::directive() to wrap Cache::tags()->remember(). Pair @cache('key', 3600) with @endcache using output buffering. Model observers listen for updated/saved events to flush cache tags by table name, ensuring automatic invalidation when data changes. View cache clears with php artisan view:clear.

Example:-

Code

// AppServiceProvider.php
public function boot()
{
    Blade::directive('cache', fn($expression) => "remember({$expression}, now()->addHour(), function() { ?>");
    Blade::directive('endcache', fn() => 'get(ob_get_clean()) ?? ob_get_clean(); ?>');
}

// app/Models/Post.php
protected static function booted()
{
    static::updated(fn($model) => Cache::tags(['views', $model->getTable()])->flush());
}