juampi92/laravel-query-cache

Provide easy interface for caching laravel queries

Fund package maintenance!
Juampi92

v1.2.0 2023-04-12 16:40 UTC

This package is auto-updated.

Last update: 2024-04-12 18:39:22 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This package provides a set of macros to cache your Laravel Queries just like Cache::remember.

$featuredPost = Post::published()->orderByMostViews()
    ->cacheDay('post:featured') // <- Here
    ->first();

Installation

You can install the package via composer:

composer require juampi92/laravel-query-cache

That's it! No config or Trait necessary. The package auto-discovery will boot the macros.

Usage

Instead of doing:

Cache::remember('post:count', $ttl, () => Post::published()->count());

You now do:

Post::published()->cache('post:count', $ttl)->count();

You can use it in Eloquent Queries as well as in normal Queries.

DB::table('posts')
    ->whereNotNull('published_at')
    ->latest()
    ->cacheHour('post:latest')
    ->first();

Posts::published()
    ->cacheHour('post:count')
    ->count();

List of macros:

Post::cache('cache:key', $ttl)->get();
Post::cacheMinute('cache:key')->first();
Post::cacheHour('cache:key')->pluck('id');
Post::cacheDay("cache:key:$id")->find($id);
Post::cacheWeek('cache:key:paginate:10')->paginate(10);
Post::cacheForever('cache:key')->count();

Advanced usage

Different store

Post::query()
    ->where(...)
    ->cache('post:count')->store('redis')
    ->count();

Add your custom cache duration

This is maybe more advanced, but you can do so by opting out of discovery, and then importing it yourself:

use Juampi92\LaravelQueryCache\LaravelQueryCacheServiceProvider as BaseServiceProvider;

class LaravelQueryCacheServiceProvider extends BaseServiceProvider
{
    protected function getCustomTimes(): array
    {
        return array_merge(
            parent::getCustomTimes(),
            [
                'rememberForever' => null,
                'cacheFifteenMinutes' => 60 * 15,
            ]
        );
    }
}

The original method has

[
    'cacheForever' => null,
    'cacheMinute' => 60,
    'cacheHour' => 60 * 60,
    'cacheDay' => 60 * 60 * 24,
    'cacheWeek' => 60 * 60 * 24 * 7,
]

Disclaimer

This package is supposed to be a nice integration of Cache remember inside the Query Builder. If you're looking for a advanced eloquent specific cache, I recommend to check out laravel-eloquent-query-cache.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.