Laravel
Laravel

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

December 3, 2025

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 ?

Ready to leverage the power of conversational AI? Start your project with Zignuts expert AI developers.
bg-image
download-image
Company Deck
PDF, 3MB
© 2026 Zignuts Technolab. All Rights Reserved.
branch imagesbranch imagesbranch imagesbranch imagesbranch imagesbranch images