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

alokin's avatar

Spatie laravel-responsecache package

Hello,

I am using Redis as cache driver.

I've followed the docs inside this package on how to put tags using middleware. So now my routes look like this:

Route::middleware('cacheResponse:news')->group(function() {
    Route::get('news', [NewsController::class, 'news'])->name('news');
    Route::get('news/{categorySlug}', [NewsController::class, 'category'])->name('news.category');
    Route::get('news/{categorySlug}/{slug}', [NewsController::class, 'single'])->name('news.single');;
});

Route::middleware('cacheResponse:blog')->group(function() {
    Route::get('{slug}', [FrontendController::class, 'resolve'])->name('resolve');
    Route::get('{catSlug}/{slug}', [FrontendController::class, 'resolveSingle'])->name('resolve.single');
});

Cache generated through first group of routes:

127.0.0.1:6379[1]> keys *
1) "laravel_database_laravel_cache:tag:news:key"
2) "laravel_database_laravel_cache:4c2bb8b160dbb3faddeb1d81ede7132b6da51323:responsecache-9d16f2cd115b0285bef9f690678649ad"
3) "laravel_database_laravel_cache:607816556bb14251306101:standard_ref"

Cache generated through second group of routes:

1) "laravel_database_laravel_cache:607816b2d89a3366874265:standard_ref"
2) "laravel_database_laravel_cache:responsecache-4d4978e18f6d15352bc61c5097f06ffc"
3) "laravel_database_laravel_cache:tag:blog:key"
4) "laravel_database_laravel_cache:8671de40b8046a43258590ffd4e31cbc44b70954:responsecache-4d4978e18f6d15352bc61c5097f06ffc"

For some reason there is always that one extra line for second group, containing responsecache- part. Lines 2 and 4 there are duplicates so deleting cache by tag, for news ResponseCache::clear(['news']) works fine, but for blog ResponseCache::clear(['blog']) deletes everything but mentioned extra line. That results in displaying wrong data on the front later, because cached page is still there.

What may be the problem here? I can provide more code if needed.

0 likes
2 replies
alokin's avatar

Okay I figured it out...partially. I've used ray() to dump $args within handle function of middleware (namespace Spatie\ResponseCache\Middlewares\CacheResponse.php) and the result was that this function is being called two times. First time it's called, it is without $args which means it is being saved with no tags. Second time it is called, I get [0 => 'blog'] inside $args. How can it be when route is within same middleware all the time?

Edit: This is for first route group, for second it's being called only once, with params as expected.

alokin's avatar

This was my mistake. I have registered middleware twice, once globally and once for routes.

1 like

Please or to participate in this conversation.