rogervila / laravel-autocache
Automatic Laravel Eloquent Models Cache
Requires
- laravel/framework: ^6.0|^7.0|^8.0
Requires (Dev)
- cache/filesystem-adapter: ^1.0
- friendsofphp/php-cs-fixer: ^2.14
- orchestra/testbench: ^3 || ^4 || ^5 || ^6
- phpunit/phpunit: ^7.5 || ^8.0 || ^9.0
- rogervila/php-sonarqube-scanner: ^0 || ^1
- swayok/alternative-laravel-cache: ^5.4
This package is auto-updated.
Last update: 2024-12-04 18:47:16 UTC
README
Laravel Autocache
About
Laravel Autocache package caches Eloquent model 'select' queries.
When a model is modified with Eloquent methods, the cache is automatically flushed.
Example
Imagine that we select all Posts with Categories using Eager Loading
Post::with('categories')->get();
This will generate two queries that will run only once:
select * from `posts` select * from `categories`
While no Post or Category model change is applied, both queries will be cached.
Now, imagine that we edit the title of our latest post
$post = Post::find($id); $post->update(['title' => 'Your edited title']); return Post::with('categories')->get();
Only the select query for posts
table will be executed, since Category model stills cached
select * from `posts`
Autocache can be disabled on runtime if necessary
Post::disableAutoCache(); // Do your database changes here Post::enableAutoCache();
Installation
Require this package with composer.
composer require rogervila/laravel-autocache
If you don't use auto-discovery, add the ServiceProvider to the providers array in config/app.php
LaravelAutoCache\AutocacheServiceProvider::class,
Now, copy the package config to your project config with the publish command:
php artisan vendor:publish --provider=" LaravelAutoCache\AutocacheServiceProvider"
Usage
First, put the models you want to handle into config/autocache.php
models key.
/** * List of models that implement autocache by default. * Models have to also implement the Autocache trait * in order to work properly */ 'models' => [ App\Product::class, ],
Then, add the Autocache
trait on the models listed on the configuration
namespace App; use Illuminate\Database\Eloquent\Model; use LaravelAutoCache\Autocache; class Product extends Model { use Autocache; ...
Troubleshooting
Autocache does not work on update queries
Check this Laravel issue comment
License
Laravel Autocache is open-sourced software licensed under the MIT license.
Icon made by Dirtyworks from www.flaticon.com is licensed by CC 3.0 BY