Cache Chunks of Your Blade Markup With Ease

Packages

March 10th, 2022

laravel-blade-cache-featured.png

Laravel Blade Cache Directive is a package by Ryan Chandler that allows you to cache chunks of Blade files. The package provides a @cache directive you can use as follows:

1{{-- Provide a cache key and TTL (default is 1 hour) --}}
2@cache('current_time', 30)
3 {{ now() }}
4@endcache

The cache block will be cached using Laravel's application cache, and even allows string interpolation if you want to cache a block in a per-model way:

1@cache("user_profile_{$user->id}")
2 {{ $user->name }}
3@endcache

If you're curious, the {{ now() }} cache block example would result in something like the following output:

1$__cache_directive_arguments = ['current_time', 300];
2 
3if (count($__cache_directive_arguments) === 2) {
4 [$__cache_directive_key, $__cache_directive_ttl] = $__cache_directive_arguments;
5} else {
6 [$__cache_directive_key] = $__cache_directive_arguments;
7 $__cache_directive_ttl = config('blade-cache-directive.ttl');
8}
9 
10if (\Illuminate\Support\Facades\Cache::has($__cache_directive_key)) {
11 echo \Illuminate\Support\Facades\Cache::get($__cache_directive_key);
12} else {
13 $__cache_directive_buffering = true;
14 
15 ob_start();
16 ?>
17 <?php echo e(now()); ?>
18 
19 <?php
20 $__cache_directive_buffer = ob_get_clean();
21 
22 \Illuminate\Support\Facades\Cache::put($__cache_directive_key, $__cache_directive_buffer, $__cache_directive_ttl);
23 
24 echo $__cache_directive_buffer;
25 
26 unset($__cache_directive_key, $__cache_directive_ttl, $__cache_directive_buffer, $__cache_directive_buffering, $__cache_directive_arguments);
27}

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners