Ryan Chandler

Caching chunks of your Blade templates

2 min read

This post was published 2 years ago. Some of the information might be outdated!

As your application grows it's likely that your Blade templates will become more and more complex. With complexity will also likely come performance penalties, especially if you're doing large loops or rendering large components in your templates.

One way of tackling this in application code is by caching things, whether it's a database query, call to an external service or some heavy computational logic. Out of the box, Blade doesn't have any caching mechanism beyond pre-compiling templates into plain PHP.

That's where my blade-cache-directive package comes into play! With this package you can cache a chunk of your Blade template and avoid unnecessary recompilation in future renders.

Begin by installing the package with Composer.

composer require ryangjchandler/blade-cache-directive

Now find the part of your Blade template that you'd like to cache and wrap it in a @cache directive.

@cache('heavy-bit-of-blade')
    @foreach($someLargeArray as $_)
        {{-- ... --}}
    @endforeach
@endcache

And now your Blade is being cached. The default TTL (time to live) set by the package is 3600 seconds, or 60 minutes. If you want to change this, you can pass a second argument to the directive.

@cache('heavy-bit-of-blade', 60)
    @foreach($someLargeArray as $_)
        {{-- ... --}}
    @endforeach
@endcache

Now it will only be cached for 60 seconds. Valid values for the TTL are the same as Laravel's own Cache methods.

One more thing to note. Since this package uses Laravel's Cache setup, clearing the cached chunk of Blade is as simple as calling Cache::forget('heavy-bit-of-blade') or clearing the application cache on deployment.

You can read more about this package on GitHub.