PHPackages                             laragear/cache-query - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. laragear/cache-query

ActiveLibrary[Database &amp; ORM](/categories/database)

laragear/cache-query
====================

Remember your query results using only one method. Yes, only one.

v6.0.0(4mo ago)272147.0k↓29.8%16MITPHPPHP ^8.3CI passing

Since Feb 16Pushed 4mo ago2 watchersCompare

[ Source](https://github.com/Laragear/CacheQuery)[ Packagist](https://packagist.org/packages/laragear/cache-query)[ Fund](https://github.com/sponsors/DarkGhostHunter)[ Fund](https://paypal.me/darkghosthunter)[ RSS](/packages/laragear-cache-query/feed)WikiDiscussions 6.x Synced 2d ago

READMEChangelog (10)Dependencies (14)Versions (30)Used By (0)

Cache Query
===========

[](#cache-query)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f5a029f7ba2bec0bb1fd37cc310e5644ad20ead39c6979065fcf40c5a63bf069/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c617261676561722f63616368652d71756572792e737667)](https://packagist.org/packages/laragear/cache-query)[![Latest stable test run](https://github.com/Laragear/CacheQuery/workflows/Tests/badge.svg)](https://github.com/Laragear/CacheQuery/actions)[![Codecov coverage](https://camo.githubusercontent.com/cf3a6b81e91bb161eaa9229f4796dc718f9fb4a86c12c467e2cc8ecb6fc3f928/68747470733a2f2f636f6465636f762e696f2f67682f4c617261676561722f436163686551756572792f67726170682f62616467652e7376673f746f6b656e3d494f5a533154464a3547)](https://codecov.io/gh/Laragear/CacheQuery)[![Maintainability](https://camo.githubusercontent.com/dafdeec54c080c1f490fa7a4ef842c351bddd2dbd7e8bbfcef21ff3cae81ff4e/68747470733a2f2f716c74792e73682f6261646765732f38373338666631332d303163612d346433382d383361382d6464343834373233303933642f6d61696e7461696e6162696c6974792e737667)](https://qlty.sh/gh/Laragear/projects/CacheQuery)[![Sonarcloud Status](https://camo.githubusercontent.com/47fad149b5a7d27fb1f7eb841e7a7ee1a4ededd049b1c7ab768d7f79119a834c/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4c617261676561725f43616368655175657279266d65747269633d616c6572745f737461747573)](https://sonarcloud.io/dashboard?id=Laragear_CacheQuery)[![Laravel Octane Compatibility](https://camo.githubusercontent.com/70359a356da237cd29561bc5d0bb80baae775b5ff62f288ed324755382858342/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2532304f6374616e652d436f6d70617469626c652d737563636573733f7374796c653d666c6174266c6f676f3d6c61726176656c)](https://laravel.com/docs/13.x/octane#introduction)

Remember your query results using only one method. Yes, only one.

```
Articles::latest('published_at')->cache()->take(10)->get();
```

Become a sponsor
----------------

[](#become-a-sponsor)

[![](.github/assets/support.png)](https://github.com/sponsors/DarkGhostHunter)

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can **spread the word in social media**

Requirements
------------

[](#requirements)

- PHP 8.3
- Laravel 12 or later

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require laragear/cache-query
```

How does it work?
-----------------

[](#how-does-it-work)

This library wraps the database connection into a proxy object. It proxies all method calls to it except `select()` and `selectOne()`.

Once a `SELECT` statement is executed through the aforementioned methods, it will check if the results are in the cache before executing the query. On cache hit, it will return the cached results, otherwise it will continue execution, save the results using the cache configuration, and return them.

Usage
-----

[](#usage)

Use the `cache()` method to remember the results of a query for a default of 60 seconds.

```
use Illuminate\Support\Facades\DB;
use App\Models\Article;

DB::table('articles')->latest('published_at')->take(10)->cache()->get();

Article::latest('published_at')->take(10)->cache()->get();
```

The next time you call the **same** query, the result will be retrieved from the cache instead of running the `SELECT` SQL statement in the database, even if the results are empty, `null` or `false`. You may also desire to [not cache empty results](#cache-except-empty-results).

It's **eager load aware**. This means that it will cache an eager loaded relation automatically (but [you may also disable this](#eager-loaded-queries)).

```
use App\Models\User;

$usersWithPosts = User::where('is_author')->with('posts')->cache()->paginate();
```

### Time-to-live

[](#time-to-live)

By default, results of a query are cached by 60 seconds, which is mostly enough when your application is getting hammered with the same query results.

You're free to use any number of seconds from now, or a `DateTimeInterface` like Carbon.

```
use Illuminate\Support\Facades\DB;
use App\Models\Article;

DB::table('articles')->latest('published_at')->take(10)->cache(120)->get();

Article::latest('published_at')->take(10)->cache(now()->addHour())->get();
```

You can also use `null`, `ever` or `forever` to set the query results forever.

```
use App\Models\Article;

Article::latest('published_at')->take(10)->cache('forever')->get();
```

### Stale while revalidate

[](#stale-while-revalidate)

You may take advantage of [Laravel Flexible Caching mechanism](https://laravel.com/docs/cache#swr) by issuing an array of values as first argument. (...) *The first value in the array represents the number of seconds the cache is considered fresh, while the second value defines how long it can be served as stale data before recalculation is necessary*.

```
use App\Models\Article;

Article::latest('published_at')->take(200)->cache([300, 60])->get();
```

The above example will refresh the query results if there is 60 seconds lefts until the data dies.

Advanced caching
----------------

[](#advanced-caching)

You may use a callback to further change the query caching. The callback receives a `Laragear\CacheQuery\Cache` instance that allows to change how to cache the data.

```
use Laragear\CacheQuery\Cache;
use App\Models\User;

User::query()->where('cool', true)->cache(function (Cache $cache) {
    $cache->ttl([300, 60])->regenWhen(true);
})->get();
```

Alternatively, you can create and configure an instance outside the query, and then pass it as an argument. You can do this with the `for()` method or `flexible()` method

```
use Laragear\CacheQuery\Cache;
use App\Models\User;
use App\Models\Post;

$cacheUser = Cache::for(30)->regenWhen(true);

User::query()->where('cool', true)->cache($cacheUser)->get();

$cachePost = Cache::flexible(300, 50)->as('frontend-posts');

Post::query()->latest()->limit(10)->cache($cachePost)->get();
```

### Conditional Regeneration

[](#conditional-regeneration)

You may want to forcefully regenerate the queried cache when the underlying data changes, or because other reason. For that, use the `regenWhen()` and a condition that evaluates to `true`, and `regenUnless()` for a condition that evaluates to `false`. If you pass a callback, it will be executed before retrieving the results from the cache.

```
use Laragear\CacheQuery\Cache;

Cache::for([300, 50])->regenWhen(true);

Cache::for(50)->regenUnless(fn() => false);
```

### Cache except empty results

[](#cache-except-empty-results)

By default, the `cache()` method will cache *any* result from the query, empty or not. You can disable this with the `exceptEmpty()` method, which will only cache non-empty results.

```
use Laragear\CacheQuery\Cache;

Cache::for(300)->exceptEmpty();
```

### Eager loaded queries

[](#eager-loaded-queries)

You may disable caching Eager Loaded Queries with the `exceptNested()` method. With that, only the query that invokes the `cache()` method will be cached.

```
use Laragear\CacheQuery\Cache;

Cache::for(300)->exceptNested();
```

For example, in this query, only the `User` query will be cached, while the `posts` won't.

```
use App\Models\User;
use App\Models\Post;
use Laragear\CacheQuery\Cache;

User::where('cool', true)
    ->cache(fn(Cache $cache) => $cache->exceptNested())
    ->with('posts', fn ($query) => $query->where('published_at', '
