Laravel Packages

Cache Chunks of Your Blade Markup With Ease

Published
Cache Chunks of Your Blade Markup With Ease image

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:

{{-- Provide a cache key and TTL (default is 1 hour) --}}
@cache('current_time', 30)
    {{ now() }}
@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:

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

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

$__cache_directive_arguments = ['current_time', 300];

if (count($__cache_directive_arguments) === 2) {
    [$__cache_directive_key, $__cache_directive_ttl] = $__cache_directive_arguments;
} else {
    [$__cache_directive_key] = $__cache_directive_arguments;
    $__cache_directive_ttl = config('blade-cache-directive.ttl');
}

if (\Illuminate\Support\Facades\Cache::has($__cache_directive_key)) {
    echo \Illuminate\Support\Facades\Cache::get($__cache_directive_key);
} else {
    $__cache_directive_buffering = true;

    ob_start();
    ?>
    <?php echo e(now()); ?>

    <?php
    $__cache_directive_buffer = ob_get_clean();

    \Illuminate\Support\Facades\Cache::put($__cache_directive_key, $__cache_directive_buffer, $__cache_directive_ttl);

    echo $__cache_directive_buffer;

    unset($__cache_directive_key, $__cache_directive_ttl, $__cache_directive_buffer, $__cache_directive_buffering, $__cache_directive_arguments);
}

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

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support image

PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support

Read article
Insert Middleware Before or After Existing Laravel Middleware image

Insert Middleware Before or After Existing Laravel Middleware

Read article
Laravel Herd 2: Coding Agents, Workspaces, and Cloud Deploys image

Laravel Herd 2: Coding Agents, Workspaces, and Cloud Deploys

Read article
Strict Request Input Casting in Laravel image

Strict Request Input Casting in Laravel

Read article
Prevent Duplicate File Uploads With Laravel Storage Dedupler image

Prevent Duplicate File Uploads With Laravel Storage Dedupler

Read article
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article