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

Lukebouch's avatar

Cache Every Query

I saw an article a month or so ago talking about how to cache every DB query during a given request. This would remove the duplicate queries I have that have in my application that is slowing things down. I can't not find the article anymore but does anyone know how this would be done?

I basically need to cache every query for that single request.

0 likes
15 replies
automica's avatar

best place to check is in the docs

cache()->remember('users', $seconds, function () {
    return DB::table('users')->get();
});

where $seconds is how long you wish to cache the response for

Lukebouch's avatar

I have been doing that but I thought there was a way to automatically cache every single query for a certain request.

automica's avatar

@Lukebouch were you looking for something like QueryCacheble?

https://github.com/renoki-co/laravel-eloquent-query-cache

use Rennokki\QueryCache\Traits\QueryCacheable;

class Article extends Model
{
    use QueryCacheable;

    /**
     * Specify the amount of time to cache queries.
     * Do not specify or set it to null to disable caching.
     *
     * @var int|\DateTime
     */
    public $cacheFor = 3600; // cache time, in seconds
}
Lukebouch's avatar

@automica That was not it. It was sometime of service provide or something like that where every single query was first checked against the cache. Not just models but literally every query.

MohamedTammam's avatar

Are you looking for caching the entire response, check that package.

PS: I didn't personally try it before.

Lukebouch's avatar

I'm justing looking to cache every query Laravel makes to the DB and store it in an array cache driver. I just want to easily remove the duplicate queries I have automatically.

tykus's avatar

This would remove the duplicate queries I have that have in my application that is slowing things down

Maybe trying to remove the duplicate queries first?

1 like
tykus's avatar

@Lukebouch the Queries tab displays the file and line number for each query executed during the request

1 like
Lukebouch's avatar

@tykus Ok I will look at that. I just though I could cache everything at the driver and then I would not need to cache each individual query I run though-out the different controllers.

martinbean's avatar
Level 80

@Lukebouch Don’t try to fix symptoms, fix the actual problems.

If you have duplicate queries then look into why you have duplicate queries and fix it. Don’t just go, “Oh, I’ll just cache everything and that’ll make things go faster”. Because misusing a cache can have the opposite affect and make things worse in your application.

Please or to participate in this conversation.