Everyone wants to load their website faster but due to low server resource, SQL query execution of the dynamic website, logic processing and some server-side stuff make it slower when website traffic increase. In this situation, we can serve our dynamic laravel website as a static HTML page with page cache with zero database query! It loads your website pages blazing fast! In this post, I'll show you step by step process for making your dynamic laravel website faster with page cache!
Install the silber/page-cache package. To do that, run the composer command given below.
composer require silber/page-cache
Register page cache middleware to http/kernel.php file.
'page-cache' => \Silber\PageCache\Middleware\CacheResponse::class,
Now add middleware to routes which you want to cache the response.
Route::get('/post/{slug}', 'SiteController@post')->middleware('page-cache');
Note: Here I have added page-cache
middleware to dynamic post route. Each page response will be cached as HTML page into our public/page-cache
directory and will serve the page super fast without touching the Laravel framework logic and database query!
Add this snippet code into your htaccess file before # Handle Front Controller...
. If you use Nginx server then follow the page-cache package documentation.
# Serve Cached Page If Available...
RewriteCond %{REQUEST_URI} ^/?$
RewriteCond %{DOCUMENT_ROOT}/page-cache/pc__index__pc.html -f
RewriteRule .? page-cache/pc__index__pc.html [L]
RewriteCond %{DOCUMENT_ROOT}/page-cache%{REQUEST_URI}.html -f
RewriteRule . page-cache%{REQUEST_URI}.html [L]
RewriteCond %{DOCUMENT_ROOT}/page-cache%{REQUEST_URI}.json -f
RewriteRule . page-cache%{REQUEST_URI}.json [L]
Delete a page cache by this artisan command.
php artisan page-cache:clear {slug}
We can use the model boot
method for deleting the page cache when post updated. After post update, it'll automatically delete the page cache and make it again when it gets the first request.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Artisan;
class Post extends Model
{
public static function boot()
{
parent::boot();
static::updated(function ($model) {
Artisan::call("page-cache:clear $model->slug");
});
}
}
Hope this post will help you to serve your dynamic laravel website as a static site by page-cache which will make your website super fast! You can read learn more about enhancing the laravel website speed post. If you find this post helpful then please share it with others.