Laravel Page Cache for Lightning Fast Page Loads
Published on by Paul Redmond
Laravel Page cache is a plugin by Joseph Silber designed to cache HTTP GET responses as static files for lightning fast page loads. This plugin gives you the benefit of a full PHP application, with the benefits of full-page static file caching for all your routes or any specific routes that are static:
While static site builders such as Jekyll and Jigsaw are extremely popular these days, dynamic PHP sites still offer a lot of value even for a site that is mostly static. A proper PHP site allows you to easily add dynamic functionality wherever needed, and also means that there’s no build step involved in pushing updates to the site.
That said, for truly static pages on a site there really is no reason to have to boot up a full PHP app just to serve a static page. Serving a simple HTML page from disk is infinitely faster and less taxing on the server.
To accomplish static file caching, you need to configure your web server to check for the static files the plugin generates. The package readme contains instructions for setting up the necessary URL rewriting for both Apache and Nginx.
Using this Page Cache plugin for full page caching couldn’t be easier. If you want every HTTP GET request in your application to get cached you can add this plugin’s middleware to the
protected $middlewareGroups = ['web' => [\Silber\PageCache\Middleware\CacheResponse::class,/* ... keep the existing middleware here */],];
You can also define this middleware as an alias and apply it to individual routes or route groups:
protected $routeMiddleware = ['page-cache' => Silber\PageCache\Middleware\CacheResponse::class,/* ... keep the existing mappings here */];
Then in an individual route, you can do the following:
Avoiding the need to hit your PHP application means that your web server can serve the fastest response possible when you are serving static content.
Check out the official package at JosephSilber/page-cache on GitHub. The author Joseph Silber is a frequent Laravel contributor, both committing to the framework, and providing excellent packages like Laravel Bouncer (we also compared Bouncer and Laravel Permission packages if you want to learn more). Joseph recently submitted a nice PR to
laravel/framework, adding the ability to pass a closure as a second argument to the optional helper.