Optimizing the speed of your website is very important. In this shot, you will learn how to improve the overall speed of your Laravel web application in a few steps.
Install the page cache package using composer
.
composer require silber/page-cache
Register the cache middleware to http/kernel.php
like so:
'page-cache' => \Silber\PageCache\Middleware\CacheResponse::class,
Now add the middleware to routes
that will have high traffic, like so:
Route::get('/post/{slug}', 'SiteController@post')->middleware('page-cache');
Edit your .htaccess
file with the code snippet below:
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]
Clear and update the page-cache
using this artisan command:
php artisan page-cache:clear {slug}
Use the model boot method to maintain dynamic deletion and update of the cached page.
<?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");
});
}
}
RELATED TAGS
CONTRIBUTOR
View all Courses