rogervila/laravel-autocache

Automatic Laravel Eloquent Models Cache

0.5.0 2020-10-05 11:59 UTC

README

Laravel Autocache

Build Status Build status StyleCI Quality Gate Status Coverage Maintainability Rating Latest Stable Version Total Downloads License

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