Run the command to make HTML minify middleware and do the code in the middleware for unifying the HTML on-page request.
php artisan make:middleware HtmlMinifier
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class HtmlMinifier
{
public function handle($request, Closure $next)
{
$response = $next($request);
$contentType = $response->headers->get('Content-Type');
if (strpos($contentType, 'text/html') !== false) {
$response->setContent($this->minify($response->getContent()));
}
return $response;
}
public function minify($input)
{
$search = [
'/\>\s+/s',
'/\s+</s',
];
$replace = [
'> ',
' <',
];
return preg_replace($search, $replace, $input);
}
}
Add the middleware into kernel.php file into the $routeMiddlewareGroup
protected $routeMiddleware = [
'HtmlMinifier' => '\App\Http\Middleware\HtmlMinifier',
]
Now we can use this middleware in our route file. For every request on our site, this middleware will automatically do HTML modification and response to the user.
Route::group(['middleware'=>'HtmlMinifier'], function(){
Route::get('/', 'SiteController@home');
});