PHPackages                             hishabee/laravel-query-cache - 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. [Caching](/categories/caching)
4. /
5. hishabee/laravel-query-cache

ActiveLibrary[Caching](/categories/caching)

hishabee/laravel-query-cache
============================

Smart SQL query caching for Laravel with tag-based invalidation

v1.0.3(1y ago)06MITPHPPHP ^7.2.5|^7.3|^7.4|^8.0

Since Dec 18Pushed 1y ago1 watchersCompare

[ Source](https://github.com/Ratul-Bin-Tazul/laravel-query-cache)[ Packagist](https://packagist.org/packages/hishabee/laravel-query-cache)[ RSS](/packages/hishabee-laravel-query-cache/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (4)Versions (4)Used By (0)

Laravel Query Cache
===================

[](#laravel-query-cache)

Smart SQL query caching for Laravel with tag-based invalidation and precise cache clearing.

Features
--------

[](#features)

- Automatic query caching with intelligent tag-based invalidation
- Support for explicit query-level cache control
- Smart cache invalidation based on WHERE clauses
- Configurable caching strategy (all queries or manual)
- Works with Laravel 7.0 and above
- Compatible with Redis and Memcached
- Cache stampede prevention

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

[](#installation)

```
composer require hishabee/laravel-query-cache
```

The package will automatically register its service provider.

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=query-cache-config
```

Add these variables to your `.env` file:

```
QUERY_CACHE_ENABLED=true
QUERY_CACHE_STRATEGY=manual
QUERY_CACHE_DURATION=3600
QUERY_CACHE_STORE=redis
```

Basic Usage
-----------

[](#basic-usage)

```
// Cache a specific query for 1 hour
User::where('active', true)
    ->cache(3600)
    ->get();

// Cache with default duration from config
Post::latest()
    ->cache()
    ->paginate();

// Disable cache for a specific query (when strategy is 'all')
Order::where('status', 'pending')
    ->cache(false)
    ->get();
```

How It Works
------------

[](#how-it-works)

### Tag-Based Caching

[](#tag-based-caching)

The package uses a sophisticated tagging system to enable precise cache invalidation:

1. **Table-Level Tags**

```
// Query:
User::where('active', true)->cache()->get();

// Generated Tags:
[
    'table:users',  // Base table tag
    'where:users:active:1'  // Condition tag
]
```

2. **Multiple Conditions**

```
// Query:
User::where('active', true)
    ->where('role', 'admin')
    ->cache()
    ->get();

// Generated Tags:
[
    'table:users',
    'where:users:active:1',
    'where:users:role:admin'
]
```

### Cache Invalidation

[](#cache-invalidation)

When a table is updated, the package intelligently invalidates only relevant cached queries:

```
// Original cached query
User::where('role', 'admin')->cache()->get();

// When this update happens:
User::where('role', 'user')->update(['active' => false]);

// Only cache entries with these tags are invalidated:
[
    'table:users',
    'where:users:role:user'
]

// The cached 'admin' query remains valid!
```

### Cache Keys

[](#cache-keys)

Cache keys are generated based on the full query including bindings:

```
$key = 'query_cache:' . md5($fullQuery);

// Example:
// SELECT * FROM users WHERE active = '1'
// Becomes: query_cache:a1b2c3d4e5f6...
```

### Smart Cache Duration

[](#smart-cache-duration)

You can set cache duration at multiple levels:

1. **Global Default** (in config)

```
'duration' => env('QUERY_CACHE_DURATION', 3600),
```

2. **Per Query**

```
User::where('active', true)
    ->cache(7200)  // Cache for 2 hours
    ->get();
```

Advanced Usage
--------------

[](#advanced-usage)

### Working with Complex Queries

[](#working-with-complex-queries)

```
// Multiple joins
User::join('orders', 'users.id', '=', 'orders.user_id')
    ->join('products', 'orders.product_id', '=', 'products.id')
    ->where('orders.status', 'completed')
    ->cache()
    ->get();

// Nested conditions
User::where(function($query) {
    $query->where('role', 'admin')
          ->orWhere('role', 'manager');
})
->cache()
->get();
```

### Manual Cache Control

[](#manual-cache-control)

```
// Clear cache for specific table
Cache::tags(['table:users'])->flush();

// Clear cache for specific condition
Cache::tags(['where:users:role:admin'])->flush();
```

### Debugging Cache Behavior

[](#debugging-cache-behavior)

Enable debug mode in your .env:

```
QUERY_CACHE_DEBUG=true
```

This will log:

- Cache hits/misses
- Generated tags
- Cache invalidations

Example log output:

```
[Query Cache] Hit: SELECT * FROM users WHERE active = '1'
[Query Cache] Tags: table:users, where:users:active:1
[Query Cache] Invalidated tags: table:users, where:users:role:admin

```

Performance Considerations
--------------------------

[](#performance-considerations)

1. **Cache Store**

    - Redis (recommended) or Memcached required for tag support
    - File cache driver doesn't support tags
2. **Cache Duration**

    - Shorter durations for frequently updated tables
    - Longer durations for static/reference data
3. **Excluded Tables**

    - Add frequently updated tables to `excluded_tables` in config
    - Consider excluding tables with sensitive data

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

MIT License. See LICENSE.md for details.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance40

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

509d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a3b1b760f0819accfed53f2bc5aa7493a76e35b3d1d9a20d8ca8d1ca3c68567b?d=identicon)[ratul38](/maintainers/ratul38)

---

Top Contributors

[![Ratul-Bin-Tazul](https://avatars.githubusercontent.com/u/18518430?v=4)](https://github.com/Ratul-Bin-Tazul "Ratul-Bin-Tazul (20 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hishabee-laravel-query-cache/health.svg)

```
[![Health](https://phpackages.com/badges/hishabee-laravel-query-cache/health.svg)](https://phpackages.com/packages/hishabee-laravel-query-cache)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[genealabs/laravel-model-caching

Automatic caching for Eloquent models.

2.4k4.8M26](/packages/genealabs-laravel-model-caching)[mikebronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k127.1k1](/packages/mikebronner-laravel-model-caching)[illuminate/cache

The Illuminate Cache package.

12835.6M1.4k](/packages/illuminate-cache)[laragear/cache-query

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

272122.8k](/packages/laragear-cache-query)[namoshek/laravel-redis-sentinel

An extension of Laravels Redis driver which supports connecting to a Redis master through Redis Sentinel.

38679.0k](/packages/namoshek-laravel-redis-sentinel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
