PHP code example of ldavidsp / laravel-varnish

1. Go to this page and download the library: Download ldavidsp/laravel-varnish library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ldavidsp / laravel-varnish example snippets


\Spatie\Varnish\VarnishServiceProvider::class

return [
    /*
     * The hostname this Laravel app is listening to.
     */
    'host' => 'example.com',

    /*
     * The location of the file containing the administrative password.
     */
    'administrative_secret' => '/etc/varnish/secret',

    /*
     * The port where the administrative tasks may be sent to.
     */
    'administrative_port' => 6082,

    /*
     * The default amount of minutes that content rendered using the `CacheWithVarnish`
     * middleware should be cached.
     */
    'cache_time_in_minutes' => 60 * 24,

    /*
     * The name of the header that triggers Varnish to cache the response.
     */
    'cacheable_header_name' => 'X-Cacheable',
];

// app/Http/Kernel.php
protected $routeMiddleware = [
...
   'cacheable' => \Spatie\Varnish\Middleware\CacheWithVarnish::class,
];

$app->configure('varnish');
$app->routeMiddleware([
...
   'cacheable' => \Spatie\Varnish\Middleware\CacheWithVarnish::class,
]);

// your routes file

//will be cached by Varnish
Route::group(['middleware' => 'cacheable'], function() {
    Route::get('/', 'HomeController@index');
    Route::get('/contact', 'ContactPageController@index');
});

//won't be cached by Varnish
Route::get('do-not-cache', 'AnotherController@index');


// Varnish will cache the responses of the routes inside the group for 15 minutes
Route::group(['middleware' => 'cacheable:15'], function() {
   ...
});

(new Spatie\Varnish\Varnish())->flush();
bash
php artisan vendor:publish --provider="Spatie\Varnish\VarnishServiceProvider" --tag="config"
bash
php artisan varnish:flush