Hardist
Hardist

Reputation: 1993

Laravel caching a query

Short and simple question. The below works:

function something() {
    $this->load(['descriptions.expenses' => function ($q) use (&$transactions) {
        $transactions = $q->where('date', '>=', $this->user->startDate())->get();
    }]);

    return $transactions;
}

It returns all expenses as expected. When I cache it, like so:

function something() {
    return cache()->rememberForever('budget_expenses_' . auth()->user()->id, function () {
        $this->load(['descriptions.expenses' => function ($q) use (&$transactions) {
            $transactions = $q->where('date', '>=', $this->user->startDate())->get();
        }]);

        return $transactions;
    });
}

It immediately returns nothing. I am just curious as to why this is happening. The reason for caching it is because it's generating a lot of queries, obviously.

The following also works as expected:

function something() {
    return cache()->rememberForever('something_' . auth()->user()->id, function () {
        return auth()->user()->budgets()->get();
    });
}

The issue is that return $transactions; this does not seem to get cached, so calling the cached key later will simply return null.

Upvotes: 0

Views: 217

Answers (2)

Hardist
Hardist

Reputation: 1993

Seems like my caching was working after all, but I wasn't making them unique for each budget, which means, for every budget, all expenses were the same, since the first one got cached...

Upvotes: 0

Nikola Gavric
Nikola Gavric

Reputation: 3543

I think that the methods on cache() like remember or rememberForever are supposed to cache the resulting data from the closure not actually return that value, you will still need to access that key to retrieve the data, something like this:

cache()->rememberForever('budget_expenses_' . auth()->user()->id, function () {
    $transactions = /* Something */;

    $this->load(['descriptions.expenses' => function ($q) use (&$transactions) {
        $transactions = $q->where('date', '>=', $this->user->startDate())->get();
    }]);

    return $transactions;
});

return cache('budget_expenses_' . auth()->user()->id);

Upvotes: 1

Related Questions