Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hameti's avatar

Laravel query builder cache

Hi Great people,

I have a serious problem which cannot find a solution for. Is there any way (package) for Laravel 6.x that allows caching queries from the query builder like DB::table('users')->cache(time, 'id_xxx')->get()

0 likes
8 replies
hameti's avatar

@chiefguru thanks but this does not allow the query builder (like DB::table()-> ...)

click's avatar

@hameti the query builder is extendable via macro's so you can do something like this:

The cacheKey is based on the raw query + the bindings to make sure select * from user where id = 1 and select * from user where id = 2 are both considered different cache entries.

Add to your AppServiceProvider

\Illuminate\Database\Query\Builder::macro('getViaCache', function ($ttl) {
    $queryCacheKey = 'query:'.md5($this->toSql() . serialize($this->getBindings()));

    return \Cache::remember($queryCacheKey, $ttl, function() {
        return $this->get();
    });
});

Testing:

\DB::enableQueryLog();
dd(
    \DB::table('users')->where('id', '>', 1)->limit(2)->getViaCache(10),
    \DB::getQueryLog()
);

Notes You can fill up your cache quite quickly this way so be careful with it. You can easily create your own version with countViaCache() or pluckViaCache() variants.

1 like
hameti's avatar

@click Hi Again. The code you provided is the best code in the world :)

Do you think that can we have it for the paginations as well?

hameti's avatar

@click Hi, thanks for the great answer. I discovered an issue with this answer. The problem is when I use Cache::forget(key) it does not remove the cache instantly but after an extra refresh of the page. I have a feeling that this is related to the bindings in Laravel and the solution would be to put your code somewhere different than AppServiceProvider. Please can you advise?

Please or to participate in this conversation.