Skip to main content
Back to packages
2,796 GitHub stars

spatie/laravel-responsecache

View on GitHub

Description

Speed up a Laravel app by caching the entire response

This Laravel package can cache an entire response. By default it will cache all successful GET requests that return text based content (such as HTML and JSON) for a week. This could potentially speed up the response quite considerably.

The first time a request comes in, the package will save the response before sending it to the user. When the same request comes in again, the cached response is returned without going through the entire application.

Here's a quick example:

use Spatie\ResponseCache\Middlewares\CacheResponse;
 
Route::middleware(CacheResponse::for(minutes(10)))->group(function () {
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{post}', [PostController::class, 'show']);
});

For pages where brief staleness is acceptable, you can use flexible caching. After the lifetime expires, the stale response is still served instantly while the cache refreshes in the background. Once the grace period is over, the cache is considered expired and the next request will be fully recalculated:

use Spatie\ResponseCache\Middlewares\FlexibleCacheResponse;
 
Route::get('/dashboard', [DashboardController::class, 'index'])
->middleware(FlexibleCacheResponse::for(lifetime: hours(1), grace: minutes(5)));

Related Content on Laravel Daily

Video

Recent Courses on Laravel Daily

Laravel 13 Starter Kit Teams and Customizations

10 lessons
33 min

Queues in Laravel 13

18 lessons
1 h 12 min read

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.