Skip to content

Instantly share code, notes, and snippets.

@bewithdhanu
Last active April 13, 2023 11:54
Show Gist options
  • Save bewithdhanu/1c5ce1532d18d9c4bfd7b9d86c5bbce7 to your computer and use it in GitHub Desktop.
Save bewithdhanu/1c5ce1532d18d9c4bfd7b9d86c5bbce7 to your computer and use it in GitHub Desktop.
Cache Eloquent Queries and Models in Laravel

Laravel Eloquent Query Cache

Laravel Eloquent Query Cache is a package that provides caching for Eloquent queries.

Installation

To install this package, run the following command:

composer require renoki-co/laravel-eloquent-query-cache

Usage

To use this package, you can simply add the Cacheable trait to your Eloquent models:

use RenokiCo\EloquentQueryCache\Cacheable;

class User extends Model {
    use Cacheable;
}

This will cache all queries performed on the User model for 60 seconds by default. You can customize the cache duration by defining a $cacheLifetime property on your model:

use RenokiCo\EloquentQueryCache\Cacheable;

class User extends Model {
    use Cacheable;

    protected $cacheLifetime = 300; // Cache queries for 5 minutes.
}

You can also cache specific queries by using the remember method:

$users = User::remember(120)->get();

This will cache the get() query for 120 seconds.

Configuration

To publish the configuration file, run the following command:

php artisan vendor:publish --provider="RenokiCo\EloquentQueryCache\CacheServiceProvider" --tag="config"

This will create a eloquent-query-cache.php file in your config directory. You can use this file to customize the package configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment