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

Xanger's avatar

Query cache does not store items

I'm getting confused, I'm trying to save a query in the caches to lighten the load:

	public function getListYearGame($year,$month) {
		if ($month < "13") {
		$expire = Carbon::now()->addMinutes(10);
		$name = 'listGame'.$month.''.$year;

		$el_giochi = Cache::remember($name, $expire, function() {
		return	InfoGame::with(
				'games:id,nome,copertina,cover,slug',
				'platform',
				'review',
				'infogame.platform')
				->whereHas('Games', function (Builder $query) {
					$query->where('active', 1);
				})
				->whereMonth('data', '=', $month)
				->whereYear('data', $year)
				->groupBy('id_game')
				->orderBy('data')
				->get();
			});

If I remove Cache::remember from this query, it works correctly, and shows me the elements. If I try to save the data in the Caches instead, it shows me the page, with no errors but no elements.

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue might be with the way the $month variable is being used inside the Cache::remember closure. Since it's a variable inside a closure, it needs to be passed in using the use keyword. Here's an updated version of the code that should work:

public function getListYearGame($year, $month)
{
    if ($month < "13") {
        $expire = Carbon::now()->addMinutes(10);
        $name = 'listGame' . $month . '' . $year;

        $el_giochi = Cache::remember($name, $expire, function () use ($month, $year) {
            return InfoGame::with(
                'games:id,nome,copertina,cover,slug',
                'platform',
                'review',
                'infogame.platform'
            )
                ->whereHas('Games', function (Builder $query) {
                    $query->where('active', 1);
                })
                ->whereMonth('data', '=', $month)
                ->whereYear('data', $year)
                ->groupBy('id_game')
                ->orderBy('data')
                ->get();
        });
    }
}

By adding use ($month, $year) after the function definition, we're telling PHP to include those variables inside the closure.

Please or to participate in this conversation.