PHP code example of vatia / laravel-varnish

1. Go to this page and download the library: Download vatia/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/ */

    

vatia / laravel-varnish example snippets


// config/app.php

'providers' => [
    ...
    Spatie\Varnish\VarnishServiceProvider::class,
];

return [

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

    /*
     * The host where the administrative tasks may be sent to.
     */
    'administrative_host' => '127.0.0.1',


    /*
     * 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,
];

// 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();

(new Spatie\Varnish\Varnish())->flush("http://example.com/page");
bash
php artisan vendor:publish --provider="Spatie\Varnish\VarnishServiceProvider" --tag="config"
bash
php artisan varnish:flush