PHPackages                             fxcjahid/laravel-eloquent-cache-magic - 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. fxcjahid/laravel-eloquent-cache-magic

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

fxcjahid/laravel-eloquent-cache-magic
=====================================

A lightweight Laravel package for automatic Eloquent query caching with zero-code auto-cache, Redis/Memcached tag support, and automatic cache invalidation

1.0.0(8mo ago)025MITPHPPHP &gt;=8.0

Since Sep 12Pushed 8mo agoCompare

[ Source](https://github.com/fxcjahid/laravel-eloquent-cache-magic)[ Packagist](https://packagist.org/packages/fxcjahid/laravel-eloquent-cache-magic)[ Docs](https://github.com/fxcjahid/laravel-eloquent-cache-magic)[ RSS](/packages/fxcjahid-laravel-eloquent-cache-magic/feed)WikiDiscussions master Synced today

READMEChangelog (4)Dependencies (9)Versions (5)Used By (0)

Laravel Eloquent Cache Magic 🪄
==============================

[](#laravel-eloquent-cache-magic-)

[![Latest Version](https://camo.githubusercontent.com/499dc246429edaef085dcd7518fe9d802e468582de54d89af52cf23ea9f1a522/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f6678636a616869642f6c61726176656c2d656c6f7175656e742d63616368652d6d61676963)](https://github.com/fxcjahid/laravel-eloquent-cache-magic/releases)[![License](https://camo.githubusercontent.com/bb8b3355df1a042a96fe55261cffde6e5a5a33cdb0444a740880a32daf2d13a3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6678636a616869642f6c61726176656c2d656c6f7175656e742d63616368652d6d61676963)](https://github.com/fxcjahid/laravel-eloquent-cache-magic/blob/main/LICENSE)[![PHP Version](https://camo.githubusercontent.com/cb7341f1f4f93a7345d8d95e89944f3b130053581702d3a94ce126a3aaf5bd05/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6678636a616869642f6c61726176656c2d656c6f7175656e742d63616368652d6d61676963)](https://packagist.org/packages/fxcjahid/laravel-eloquent-cache-magic)[![Laravel Version](https://camo.githubusercontent.com/4f56b721d6129d21b974aad5bd0d89b049835f9f5905867bd7d21f8f32506d02/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e7825323025374325323031312e7825323025374325323031322e782d6f72616e6765)](https://laravel.com)

A lightweight Laravel package that adds intelligent caching to your Eloquent queries with zero effort. Features include automatic cache invalidation, Redis/Memcached tag support, and flexible caching options!

📖 **[Read Complete Documentation](./DOCUMENTATION.md)** - Everything you need to know in one place

✨ Features
----------

[](#-features)

- 🚀 **Zero Configuration** - Works out of the box with sensible defaults
- 🎉 **Automatic Query Caching** - All queries automatically cached without code changes!
- 🏷️ **Cache Tags Support** - Full support for Redis and Memcached tagged caching
- 🔄 **Automatic Cache Invalidation** - Cache automatically clears on model create, update, delete
- 🔧 **Flexible API** - Multiple ways to configure caching per query
- 🌐 **Multi-Driver Support** - Works with Redis, Memcached, File, Database drivers
- 🧪 **Fully Tested** - Comprehensive test coverage with PHPUnit and Pest
- 👤 **Auto User/Guest Tags** - Automatic user-specific cache isolation
- 🚫 **doNotCache() Method** - Disable caching for specific queries (DataTables compatible)
- 🎯 **Helper Functions** - Convenient global functions for cache operations

📋 Requirements
--------------

[](#-requirements)

- PHP 8.0 - 8.4
- Laravel 10.0 - 12.0
- Redis or Memcached (optional, for tag support)

📦 Installation
--------------

[](#-installation)

```
composer require fxcjahid/laravel-eloquent-cache-magic
```

### Optional: Publish Configuration

[](#optional-publish-configuration)

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

### Recommended: Setup Redis for Tag Support

[](#recommended-setup-redis-for-tag-support)

```
composer require predis/predis
```

```
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
```

#### Also update config/database.php

[](#also-update-configdatabasephp)

```
'redis' => [
    'client' => env('REDIS_CLIENT', 'predis'),
]
```

🚀 Quick Start
-------------

[](#-quick-start)

### 🎉 Automatic Query Caching

[](#-automatic-query-caching)

With auto-cache enabled, ALL your queries are automatically cached without any code changes:

```
use App\Models\User;
use App\Models\Product;

// These queries are AUTOMATICALLY cached (no ->cache() needed!)
$users = User::all();                          // Auto-cached!
$product = Product::find(1);                   // Auto-cached!
$count = User::where('active', true)->count(); // Auto-cached!

// Bypass auto-cache when you need fresh data
$freshUsers = User::withoutCache()->get();     // Skip cache
$freshProduct = Product::fresh()->find(1);     // Skip cache

// Disable auto-cache for specific models
class Order extends Model {
    use CacheableTrait;
    protected $autoCache = false;  // Disable auto-cache for this model
}
```

### Manual Caching (Traditional Method)

[](#manual-caching-traditional-method)

You can still manually control caching with the `->cache()` method:

```
// Manually cache the query
$users = User::where('active', true)->cache()->get();

// Cache for specific duration (in seconds)
$users = User::where('active', true)->cache(3600)->get(); // 1 hour

// Cache with tags (Redis/Memcached only)
$users = User::where('active', true)
    ->cache()
    ->tags(['users', 'active'])
    ->get();

// Clear cache by tags
Cache::tags(['users'])->flush(); // Only clears 'users' tagged cache
```

### Model Integration

[](#model-integration)

```
use Illuminate\Database\Eloquent\Model;
use Fxcjahid\LaravelEloquentCacheMagic\Traits\CacheableTrait;

class Product extends Model
{
    use CacheableTrait;

    protected $cacheExpiry = 7200; // 2 hours
    protected $cacheTags = ['products'];
}
```

🎯 Key Features Explained
------------------------

[](#-key-features-explained)

### 🎉 Automatic Query Caching

[](#-automatic-query-caching-1)

Enable automatic caching for ALL queries without changing your code:

```
// In config/cache-magic.php
'auto_cache' => [
    'enabled' => true,              // Enable auto-caching
    'ttl' => 3600,                  // Default 1 hour
    'aggregate_ttl' => 300,         // 5 min for count/sum/avg
    'find_ttl' => 7200,             // 2 hours for find()
],
```

Once enabled, all your existing queries are automatically cached:

```
// These are ALL automatically cached now!
User::all();                        // Cached for 1 hour
Product::find($id);                 // Cached for 2 hours
Order::count();                     // Cached for 5 minutes
Invoice::where('paid', true)->get(); // Cached for 1 hour

// Need fresh data? Bypass cache:
User::withoutCache()->all();        // Direct from database
Product::fresh()->find($id);        // Direct from database
```

### Cache Tags - Smart Invalidation

[](#cache-tags---smart-invalidation)

```
// Cache with tags for smart invalidation
$products = Product::where('category', 'electronics')
    ->cache()
    ->tags(['products', 'electronics'])
    ->get();

// Clear all electronics products
Cache::tags(['electronics'])->flush();

// Clear all products
Cache::tags(['products'])->flush();
```

### Automatic Cache Invalidation

[](#automatic-cache-invalidation)

```
class Product extends Model
{
    use CacheableTrait;

    // Cache automatically clears when model is updated/deleted
    protected $cacheTags = ['products'];

    // Dynamic tags based on attributes
    public function dynamicCacheTags(): array
    {
        return [
            'category:' . $this->category_id,
            'brand:' . $this->brand_id,
        ];
    }
}
```

### User/Guest Isolation

[](#userguest-isolation)

Automatically isolate cache by user or guest session:

```
// In config/cache-magic.php
'auto_user_tags' => [
    'enabled' => true,
    'guest_fallback' => 'session', // Options: 'session', 'ip', 'unique'
],
```

📊 Console Commands
------------------

[](#-console-commands)

```
# Clear cache by tags
php artisan cache-magic:clear --tags=products

# Clear cache by model
php artisan cache-magic:clear --model=Product

# Clear all cache
php artisan cache-magic:clear --all
```

🔧 Helper Functions
------------------

[](#-helper-functions)

```
// Cache a callback result
$users = cache_remember(['ttl' => 3600, 'tags' => ['users']], function() {
    return User::all();
});

// Clear cache by tags
cache_clear_tags(['products', 'electronics']);

// Clear cache by model
cache_clear_model(Product::class);

// Clear user-specific cache
cache_clear_user($userId);

// Clear guest cache
cache_clear_guest($guestId);

// Check if cache supports tags
if (cache_supports_tags()) {
    // Use tag-based caching
}
```

📖 Complete Documentation
------------------------

[](#-complete-documentation)

**[Read the complete documentation](./DOCUMENTATION.md)** for comprehensive details on:

- ✅ Installation and configuration
- ✅ All query methods and parameters
- ✅ Cache tags explained with examples
- ✅ Model integration guide
- ✅ Console commands usage
- ✅ Helper functions
- ✅ Advanced features
- ✅ Troubleshooting guide

🧪 Testing
---------

[](#-testing)

```
# Run tests
vendor/bin/pest

# With coverage
vendor/bin/pest --coverage
```

🤝 Contributing
--------------

[](#-contributing)

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

📝 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

👨‍💻 Author
----------

[](#‍-author)

**FXC Jahid**

- GitHub: [@fxcjahid](https://github.com/fxcjahid)
- Email:

🌟 Support
---------

[](#-support)

If you find this package helpful, please give it a ⭐ on [GitHub](https://github.com/fxcjahid/laravel-eloquent-cache-magic)!

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance59

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

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 ~12 days

Total

4

Last Release

258d ago

Major Versions

0.3 → 1.0.02025-10-20

PHP version history (3 changes)0.1PHP ^8.0|^8.1|^8.2|^8.3

0.2PHP ^8.0|^8.1|^8.2|^8.3|^8.4

1.0.0PHP &gt;=8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/33903532?v=4)[Mohammad Jahid](/maintainers/fxcjahid)[@fxcjahid](https://github.com/fxcjahid)

---

Top Contributors

[![fxcjahid](https://avatars.githubusercontent.com/u/33903532?v=4)](https://github.com/fxcjahid "fxcjahid (13 commits)")

---

Tags

laravelperformanceeloquentrediscachememcachedoptimizationtagsquery builderinvalidationauto-cacheautomatic-cachingzero-configuration

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/fxcjahid-laravel-eloquent-cache-magic/health.svg)

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M96](/packages/mongodb-laravel-mongodb)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k32.6M46](/packages/kirschbaum-development-eloquent-power-joins)[ymigval/laravel-model-cache

Laravel package for caching Eloquent model queries

7962.6k4](/packages/ymigval-laravel-model-cache)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

592456.3k2](/packages/spiritix-lada-cache)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)

PHPackages © 2026

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