DEV Community

Cover image for Database Cache for Laravel
Lito
Lito

Posted on

Database Cache for Laravel

Today I have released my new Laravel package Laravel Database Cache https://github.com/eusonlito/laravel-database-cache

This package allow to cache database queries from Models without pain.

You can configure the cache to use tags (on redis) and flush all database caches at once: https://github.com/eusonlito/laravel-database-cache#flush-caches

You can install the package via composer:

composer require eusonlito/laravel-database-cache
Enter fullscreen mode Exit fullscreen mode

Publish the default configuration in config/database-cache.php:

php artisan vendor:publish --tag=eusonlito-database-cache
Enter fullscreen mode Exit fullscreen mode

Add this lines to .env file:

DATABASE_CACHE_ENABLED=true
DATABASE_CACHE_DRIVER=redis
DATABASE_CACHE_TTL=3600
DATABASE_CACHE_TAG=database
DATABASE_CACHE_PREFIX=database|
Enter fullscreen mode Exit fullscreen mode

And configure your models to use the cache method with:

<?php declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Eusonlito\DatabaseCache\CacheBuilderTrait;

class User extends Model
{
    use CacheBuilderTrait;
Enter fullscreen mode Exit fullscreen mode

Now, the simple way to use is:

$articles = Article::latest('published_at')->take(10)->cache()->get();
Enter fullscreen mode Exit fullscreen mode

The results will be cached every time you will call this query.

Also you can set a custom cache time for this query:

$articles = Article::latest('published_at')->take(10)->cache(60)->get();
Enter fullscreen mode Exit fullscreen mode

Or a custom cache name:

$articles = Article::latest('published_at')->take(10)->cache(60, 'latest_articles')->get();
Enter fullscreen mode Exit fullscreen mode

You have more info at package https://github.com/eusonlito/laravel-database-cache

Enjoy!

Top comments (0)