Blog Detail

22

Mar
Cache Chunks of Your Blade Markup with Ease in Laravel cover image

arrow_back Cache Chunks of Your Blade Markup with Ease in Laravel

Ryan Chandler has introduced an amazing package called Blade-cache-directive that enables you to cache the chunks of your Blade markup easily in Laravel. This package offers a @cache directive that you can utilize in your project:

@cache('current_time', 30)
    {{ now() }}
@endcache

Installation

You can install the package via Composer by running this command in the terminal:

composer require ryangjchandler/blade-cache-directive

You can publish the config file with:

php artisan vendor:publish --provider="RyanChandler\BladeCacheDirective\BladeCacheDirectiveServiceProvider" --tag="blade-cache-directive-config"

This is the contents of the published config file:

return [

    'ttl' => 3_600,

];

Usage

This package adds a new @cache Blade directive. It accepts 2 arguments - the cache key and a TTL.

@cache('current_time', 30)
    {{ now() }}
@endcache

When used inside of a Blade template, the content between the 2 directives will be cached using Laravel’s application cache. If a TTL (in seconds) isn’t provided, the default TTL of 1 hour will be used instead.

If you want to cache the content for a particular model, i.e. a User model, you can use string interpolation to change the key.

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

When a new user is passed to this view, a separate cache entry will be created.

Above are the basic details and usage examples of this package. If you want to dig more, you can visit the complete documentation and source code of this package on Github.

Published at : 22-03-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project