1. Introduction
Pjax is a jQuery plugin that uses Ajax to speed up page load times by fetching only the specified HTML fragment from the server and then updating the local page with the content that the client obtains.
The Laravel Pjax expansion pack integrates Pjax into Laravel, and the implementation principle is to provide a middleware that returns the desired response content of Pjax.
2. Installation
To install an expansion pack through Composer:
$ composer require Spatie/laravel-pjax
The next step is to register the middleware in kernel.php, where we register it with the Web middleware group:
app/http/kernel.phpprotected $middlewareGroups = [ ' web ' = [ ... \spatie\pjax\middleware\filterifpjax::class, ], ...];
3. Use
The middleware provided by the extension package processes the content returned by the server and translates it into what the Pjax plug-in expects the server to return.
Here we illustrate the use of the default view file generated by the PHP Artisan Make:auth command As an example, first we modify the routing file routes.php:
Route::group ([' middleware ' = ' web '], function () { route::get ('/', function () { return view (' Welcome '); }); Route::get ('/home ', ' Homecontroller@index '); Route::auth ();});
Then we also need to modify the default layout file layouts/app.blade.php, adding Pjax settings:
... @yield (' content ')
{{--- }}
So that we can access the test in the browser:
You will find that the page does not jump to refresh directly when the login/registration button is toggled.
Note: The expansion pack sets a X-ajax request header to differentiate between Pjax requests and normal XHR requests. In this case, if the request is Pjax, we will skip the page layout part of HTML and render only the main part of the page.
Laravel Cache Invalidation
We use Laravel Elixir to manage front-end cache invalidation, and you can use this method to invalidate the Pjax cache-just introduce the Elixir method as the content of the X-pjax-version meta:
If it is multiple files, this is used:
In this case, if the front-end cache fails, then the Pjax cache automatically fails.